#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2023 Siglent <angel.xu@siglent.com>

"""
VISA连接设备的基础类
"""
import pyvisa as visa
import logging
import array

class LibVisa(object):
    def __init__(self, device_name=None, log=None):
        self.__rm = visa.ResourceManager()
        self._device = None
        self.log = log
        self.logFlag = True
        if device_name:
            device_list = self.list_device()
            for index in range(len(device_list)):
                if device_list[index] == device_name:
                    if self.connect(device_name):
                        self.write_log('Connected to USB ID {}'.format(device_name))
                        break
                    else:
                        exit()
            else:
                self.write_error_log("Can't find the device:" + device_name)
                logging.error("Can't find the device:" + device_name)
                exit()
        else:
            pass

    def __del__(self):
        if self._device:
            self._device.close()

    def list_device(self):
        return self.__rm.list_resources()

    def connect(self, device_name):
        ren = True
        try:
            self._device = self.__rm.open_resource(device_name)
            self._device.clear()#20230803byangel:避免传输打断引起下一次问询异常
            self._device.chunk_size = 20*1024*1024#20230803byangel:default is 20*1024
            # self._device.read_termination = "\n"#20230728byangel:usbtmc通信时需屏蔽此行，否则会截断
        except:
            self.write_error_log("Fail to open the device:" + device_name)
            logging.error("Fail to open the device:" + device_name)
            ren = False
        return ren

    def remove(self):
        self._device.close()

    def lock(self):
        self._device.lock_excl()

    def unlock(self):
        self._device.unlock()

    def write(self, command):
        #if self.logFlag::
        self.write_log('SEND >  ' + str(command))
        self._device.write(command)

    def read(self):
        response = self._device.read()
        #if self.logFlag::
        self.write_log('RECV >  ' + str(response))
        return response

    def query(self, command, delay=None):
        """VISA 通信接口查询命令"""
        self.write_log('SEND >  ' + str(command))
        response = self._device.query(command, delay)
        self.write_log('RECV >  ' + str(response))
        return response

    def write_raw(self, command):
        return self._device.write_raw(command)

    def read_raw(self, size=None):
        return self._device.read_raw(size)

    def set_timeout(self, value=2000):
        self._device.timeout = value

    def get_timeout(self):
        return self._device.timeout

    def write_log(self, message):
        if not self.log or not self.logFlag:
            return
        if len(message) > 500:
            self.log.write(len(message))
        else:
            self.log.write(message)

    def write_error_log(self, message):
        if not self.log or not self.logFlag:
            return
        self.log.writeError(message)

import math,re,struct
import time

_MEAERROR = -9999.99
_SCPI_NONE = "None"
_WF_DESC_LEN = 347

class LibSDS(LibVisa):
    __version__ = '4.2'
    """SDS通用接口类"""
    def __init__(self, device_name=None, log = None):
        """初始化函数
        Args：
            device_name: 设备名称

        Raises：
            带参数初始化时没有连接到设备
        """
        super(LibSDS, self).__init__(device_name, log)
        self.write("CHDR OFF")# 设置返回值格式为只返回结果
        self.SCPI_NEW_FLAG = True#testbase初始化时会根据机型重置此属性

    def __del__(self):
        """析构函数"""
        self.remove()
        # super(LibSDS, self).__del__()

    # --------------------------------------------------------------------------
    #
    # Common Method
    #
    # --------------------------------------------------------------------------
    def value_strip_unit(self, value, unit_string=None):
        """IU国际化处理"""
        try:
            if unit_string != None:
                if re.search(unit_string, value):
                    value = value.replace(unit_string, "")
            else:
                unit = ["Sa/s","dBV","dB","V","S","Hz"]
                for suffix in unit:
                    if re.search(suffix, value):
                        value = value.replace(suffix, "")
                        break

                magnitude = ["G","M","K","k","m","u","n","p"]
                atten = [1.0E+09,1.0E+06,1.0E+03,1.0E+03,1E-3,1E-6,1E-9,1E-12]
                for suffix in magnitude:
                    if re.search(suffix, value):
                        value = float(value.replace(suffix, ""))
                        value *= atten[magnitude.index(suffix)]
                        break
            value = float(value)
        except:
            value = _MEAERROR
        return value

    # --------------------------------------------------------------------------
    #
    # Format
    #
    # --------------------------------------------------------------------------
    def set_data_format(self, precision=3, mode = "CUSTom"):
        """设置询问时示波器返回命令的格式
        Args:
            precision = NR1,{0-64}
            mode: {DOUBle, SINGle, CUSTom},DOUBle=14,SINGle=7
        """
        command = "FORM:DATA " + mode.upper()
        if mode == "CUSTom":
            command = "{},{}".format(command,precision)
        self.write(command)

    def get_data_format(self):
        """获取询问时示波器返回命令的格式"""
        command = "FORM:DATA?"
        return self.query(command).rstrip()

    # --------------------------------------------------------------------------
    #
    # Autoset
    #
    # --------------------------------------------------------------------------
    def set_auto_setup(self):
        """设置一次AutoSet"""
        if self.SCPI_NEW_FLAG:
            command = "AUT"
        else:
            command = "ASET"
        self.write(command)
        flag = self.get_reg_opc()
        time.sleep(2)

    # --------------------------------------------------------------------------
    #
    # Channel
    #
    # --------------------------------------------------------------------------
    def ch_string_adapter(self,src):
        ch = src.replace("C","CHAN")
        return ch

    def bwl_string_adapter(self,state, flag):
        """set input new->output old;get input old->output new;
        flag=True,设置适配；flag=False,获取适配"""
        Param_new = ["FULL", "20M", "200M"]
        Param_old = ["OFF", "ON"]
        if flag:
            index = Param_new.index(state)
            if index > len(Param_new)-1:
                index = 1
            bwl = Param_old[index]
        else:
            index = Param_old.index(state)
            bwl = Param_new[index]
        return bwl

    def coupl_string_adapter(self,state, flag):
        """set input old->output new;get input new->output old
        flag=True,设置适配；flag=False,获取适配"""
        Param_old = ["D1M", "A1M","D50","A50","GND"]
        Param_new = [["DC", "ONEMeg"], ["AC", "ONEMeg"], ["DC", "FIFTy"], ["AC", "FIFTy"], ["GND"]]
        if flag:
            index = Param_old.index(state)
            cpl = Param_new[index]
        else:
            if "GND" in state:
                cpl = Param_old[4]
            else:
                index = Param_new.index(state)
                cpl = Param_old[index]
        return cpl

    def get_ch_num(self):
        """获取设备的通道个数"""
        if self.SCPI_NEW_FLAG:
            command = "CHAN:COUN?"
        else:
            command = "CHS?"
        rcv = self.query(command).rstrip()
        return int(rcv)

    def set_ch_trace_status(self, source, state):
        """设置通道状态
        source=["C1","C2","C3","C4"]
        state=["ON", "OFF"]
        """
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":SWIT "
        else:
            keyword = ":TRA "
        command = source.upper()+ keyword + state.upper()
        self.write(command)

    def get_ch_trace_status(self, source):
        """获取通道状态
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":SWIT?"
        else:
            keyword = ":TRA?"
        status = self.query(source + keyword)
        return status.rstrip()

    def set_ch_priority(self, source, num):
        """设置通道优先级
        source=["C1","C2","C3","C4"]
        num=[0,1,2,3]
        """
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)

            command = source + ":PR "+ str(num)
        else:
            command = source.upper() + ":PRI " + str(num)
        self.write(command)

    def get_ch_priority(self, source):
        """获取通道优先级
        source=["C1","C2","C3","C4"]
        """
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":PR?"
        else:
            command = source + ":PRI?"
        rtn = self.query(command).rstrip()
        return int(rtn)

    def set_ch_bwl(self,state,source):
        """设置带宽限制状态
        source=["C1","C2","C3","C4"]
        state=["FULL", "20M", "25M", "200M","CUSTom,xxx"]
        """
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":BWL " + state.upper()
        else:
            state = self.bwl_string_adapter(state, True)
            command = "BWL " + source.upper() + "," + state.upper()
        self.write(command)

    def get_ch_bwl(self, source):
        """获取带宽限制状态
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
        command = source.upper()+":BWL?"
        bwl = self.query(command).rstrip()
        if not self.SCPI_NEW_FLAG:
            bwl = self.bwl_string_adapter(bwl, False)
        return bwl

    def set_ch_vdiv(self, source, vdiv):
        """设置电压档位
        source=["C1","C2","C3","C4"]
        vdiv=以"V"为单位"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = "{}:SCAL {}".format(source,vdiv)
        else:
            keyword = ":VDIV "
            if type(vdiv) is str:
                command = source.upper() + keyword + vdiv.upper()
            else:
                command = source.upper() + keyword + str(vdiv) + "V"
        self.write(command)

    def get_ch_vdiv(self, source):
        """获取电压档位
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":SCAL?"
        else:
            keyword = ":VDIV?"
        command = source.upper() + keyword
        value = self.query(command).rstrip()
        return float(value)

    def set_ch_offset(self, source, offset):
        """设置通道电压offset
        source=["C1","C2","C3","C4"]
        offset=以"V"为单位"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = "{}:OFFS {}".format(source,offset)
        else:
            keyword = ":OFST "
            if type(offset) is str:
                command = source.upper() + keyword + offset.upper()
            else:
                command = source.upper() + keyword + str(offset) + "V"
        self.write(command)

    def get_ch_offset(self, source):
        """查询垂直位置
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":OFFS?"
        else:
            keyword = ":OFST?"
        command = source.upper()+keyword
        recv = self.query(command).rstrip()
        if "*" in recv:
            value = _MEAERROR
        else:
            try:
                value = self.value_strip_unit(recv,"V")
            except:
                value = _MEAERROR
        return value

    def set_ch_coupl_impd(self, source, coupl):#angel:此接口保留，已新增两条接口分别设置coupl、impedance
        """设置通道耦合阻抗
        source=["C1","C2","C3","C4"]
        coupl=["D1M", "A1M","D50","A50","GND"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            coupimp = self.coupl_string_adapter(coupl.upper(),True)
            command = source.upper() + ":COUP " + coupimp[0]
            self.write(command)
            if "GND" not in coupimp:
                command = source.upper() + ":IMP " + coupimp[1]
                self.write(command)
        else:
            command = source.upper() + ":CPL " + coupl.upper()
            self.write(command)

    def get_ch_coupl_impd(self, source="C1"):#angel:此接口保留，已新增两条接口分别获取coupl、impedance
        """获取通道耦合阻抗
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":COUP?"
            cpl = self.query(command).rstrip()
            command = source.upper() + ":IMP?"
            imp = self.query(command).rstrip()
            coupimp = self.coupl_string_adapter([cpl,imp], False)
        else:
            command = source.upper() + ":CPL?"
            coupimp = self.query(command).rstrip()
        return coupimp

    def set_ch_coupl(self, source, coupl):  # todo 适配旧指令
        """设置通道耦合，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":COUP " + coupl.upper()
            self.write(command)

    def get_ch_coupl(self, source):  # todo 适配旧指令
        """获取通道耦合，仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":COUP?"
            cpl = self.query(command).rstrip()
            return cpl
        else:
            return _SCPI_NONE

    def set_ch_impedance(self, source, imp):
        """设置通道阻抗，仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]
        imp=["ONEMeg","FIFTy"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":IMP " + imp.upper()
            self.write(command)

    def get_ch_impedance(self, source):
        """获取通道阻抗，仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source.upper() + ":IMP?"
            imp = self.query(command).rstrip()
            return imp
        else:
            return _SCPI_NONE

    def set_ch_probe(self, source, probe):
        """设置通道衰减倍数
        source=["C1","C2","C3","C4"]
        probe= in NR3 format,the range is [1E-6, 1E6]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":PROB VAL,"
        else:
            keyword = ":ATTN "
        command = source.upper()+ keyword + str(probe)
        self.write(command)

    def get_ch_probe(self, source):
        """获取通道衰减倍数
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":PROB?"
        else:
            keyword = ":ATTN?"
        command = source.upper()+keyword
        rcv = self.query(command).rstrip()
        try:
            value = float(rcv)
        except ValueError:
            value = _MEAERROR
        return value

    def set_ch_hadj(self, source, hadj):
        """设置通道粗细调,仅供self.SCPI_NEW_FLAG=False时使用
        source=["C1","C2","C3","C4"]
        HADJ = ["COARSE","FINE"]
        """
        if not self.SCPI_NEW_FLAG:
            command = source.upper()+":HADJ " + str(hadj)
            self.write(command)

    def get_ch_hadj(self, source):
        """获取通道粗细调，仅供self.SCPI_NEW_FLAG=False时使用
        source=["C1","C2","C3","C4"]"""
        if not self.SCPI_NEW_FLAG:
            command = source.upper()+":HADJ?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_ch_trace_invert(self, source, state):
        """设置通道波形反相
        source={C1,C2,C3,C4}
        state=["ON","OFF"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":INV "
        else:
            keyword = ":INVS "
        command = source.upper() + keyword + state.upper()
        self.write(command)

    def get_ch_trace_invert(self, source):
        """获取通道波形反相状态
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            keyword = ":INV?"
        else:
            keyword = ":INVS?"
        command = source.upper() + keyword
        return self.query(command).rstrip()

    def set_ch_unit(self, source, unit):
        """设置通道单位
        source=["C1","C2","C3","C4"]
        unit=["A","V"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
        command = source.upper() + ":UNIT " + unit.upper()
        self.write(command)

    def get_ch_unit(self, source):
        """获取通道单位，以字符串形式返回
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
        command = source.upper() + ":UNIT?"
        return self.query(command).rstrip()

    def set_ch_skew(self, skew, source):
        """设置时滞
        source=["C1","C2","C3","C4"]
        skew:value in NR3 format,the value is [-1.00E-07, 1.00E-07]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            if type(skew) is str:
                command = source.upper() + ":SKEW " + skew.upper()
            else:
                command = source.upper() + ":SKEW " + str(skew)+"S"
        self.write(command)

    def get_ch_skew(self, source):
        """获取时滞，以字符串形式返回
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
        command = source.upper() + ":SKEW?"
        recv =  self.query(command).rstrip()
        try:
            value = self.value_strip_unit(recv, "S")
        except:
            value = _MEAERROR
        return value

    def set_ch_label_state(self, source, state):
        """设置标签状态,仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]
        state=["ON","OFF"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":LAB " + state.upper()
            self.write(command)

    def get_ch_label_state(self, source):
        """获取标签状态,仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":LAB?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_ch_label_text(self,source, txt):
        """设置标签内容,仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]
        txt=quoted string of ASCII text. The length of the string is limited to 20."""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":LAB:TEXT \"{}\"" .format( txt.upper())
            self.write(command)

    def get_ch_label_text(self,source):
        """获取标签内容,仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":LAB:TEXT?"
            rtn =  self.query(command).rstrip()
            return rtn.strip("\"")
        else:
            return _SCPI_NONE

    def set_ch_trace(self, source,state):
        """设置波形隐藏/显示,仅供self.SCPI_NEW_FLAG=True时使用
        source=["C1","C2","C3","C4"]
        state=["ON","OFF"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":VIS " + state.upper()
            self.write(command)

    def get_ch_trace(self,source):
        """获取波形隐藏状态
        source=["C1","C2","C3","C4"]"""
        if self.SCPI_NEW_FLAG:
            source = self.ch_string_adapter(source)
            command = source + ":VIS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_ch_vertical_ref(self, type):
        """设置垂直参考策略, 仅供self.SCPI_NEW_FLAG = True时使用
        type = ["POSition", "OFFSet"]"""
        if self.SCPI_NEW_FLAG:
            command =  "CHAN:REF " + type.upper()
            self.write(command)

    def get_ch_vertical_ref(self):
        """获取垂直参考策略"""
        if self.SCPI_NEW_FLAG:
            command = "CHAN:REF?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    # --------------------------------------------------------------------------
    #
    # Timebase
    #
    # --------------------------------------------------------------------------
    def set_timebase(self, timebase):
        """设置时基
        timebase：以"s"为单位"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:SCAL {}".format(timebase)
        else:
            keyword="TDIV "
            if type(timebase) is str:
                command = keyword + timebase.upper()
            else:
                command = keyword + str(timebase) + "S"
        self.write(command)

    def get_timebase(self):
        """获取时基"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:SCAL?"
        else:
            keyword="TDIV?"
        rcv = self.query(keyword).rstrip()
        flast = self.value_strip_unit(rcv, "S")
        return flast

    def set_timebase_delay(self, delay):
        """设置时基延迟
        delay:以"s"为单位，且均以水平中心为0，左负右正"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:DEL {}".format(-delay)#20210528-平台(ZDL_V1320已修改TIM:DEL以触发为0，左负右正，固需取反)
        else:
            keyword="TRDL "
            if type(delay) is str:
                command = keyword + delay.upper()
            else:
                command = keyword + str(delay) + "S"
        self.write(command)

    def get_timebase_delay(self):
        """获取时基延迟，返回值均以水平中心为0，左负右正"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:DEL?"#20210528-平台(ZDL_V1320已修改TIM:DEL以触发为0，左负右正，固需取反)
            rcv = self.query(keyword).rstrip()
            flast = self.value_strip_unit(rcv, "S")
            flast = -flast
        else:
            keyword = "TRDL?"
            rcv = self.query(keyword).rstrip()
            flast = self.value_strip_unit(rcv, "S")
        return flast

    def set_hrz_zoom_tdiv(self, timebase):
        """设置水平扩展时基
        timebase:以"s"为单位"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:WIND:SCAL {}".format(timebase)
        else:
            keyword = "HMAG "
            if type(timebase) is str:
                command = keyword + timebase.upper()
            else:
                command = keyword + str(timebase) + "S"
        self.write(command)

    def get_hrz_zoom_tdiv(self):
        """获取水平扩展时基"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:WIND:SCAL?"
        else:
            keyword = "HMAG?"
        rcv = self.query(keyword).rstrip()
        flast = self.value_strip_unit(rcv, "S")
        return flast

    def set_hrz_zoom_pos(self, pos):
        """设置水平扩展的水平位置
        pos:以"s"为单位"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:WIND:DEL {}".format(pos)
        else:
            keyword = "HPOS "
            if type(pos) is str:
                command = keyword + pos.upper()
            else:
                command = keyword + str(pos) + "S"
        self.write(command)

    def get_hrz_zoom_pos(self):
        """获取水平扩展的水平位置"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:WIND:DEL?"
        else:
            keyword = "HPOS?"
        rcv = self.query(keyword).rstrip()
        flast = self.value_strip_unit(rcv, "S")
        return flast

    def set_zoom_switch(self, mode):
        """设置水平扩展的开关状态
        mode=["ON","OFF"]"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:WIND "
        else:
            keyword = "HSTA "
        command =keyword + mode.upper()
        self.write(command)

    def get_zoom_switch(self):
        """获取水平扩展的开关状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "TIM:WIND?"
        else:
            keyword = "HSTA?"
        return self.query(keyword).rstrip()

    def set_hrz_ref(self, type):
        """设置水平参考策略,仅供self.SCPI_NEW_FLAG = True时使用
        type = ["POSition", "DELay"]"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:REF "+ type.upper()
            self.write(command)

    def get_hrz_ref(self):
        """获取水平参考策略"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:REF?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_hrz_ref_pos(self, pos):
        """设置水平参考中心,仅供self.SCPI_NEW_FLAG = True时使用
        pos=0-100"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:REF:POS {}".format(pos)
            self.write(command)

    def get_hrz_ref_pos(self):
        """获取水平参考中心,仅供self.SCPI_NEW_FLAG = True时使用"""
        if self.SCPI_NEW_FLAG:
            command = "TIM:REF:POS?"
            val = self.query(command).rstrip()
            return float(val)

    # ---------------------------------------------------------------------------
    #
    # Trigger
    #
    # ---------------------------------------------------------------------------
    # Trigger接口封装规则：
    # 1、set_trig_type()已有接口，只处理type+source，入参均为老风格
    # 2、set_trig_edge/slope/pulse()类，入参均为老风格-angel：后续可能要修改接口名称set_trig_pulse_parameter()，
    # 3、set_trig_couple/slope/level,set_edge_trig_holdoff 类已有接口，需保留，增加type=None
    # 4、新增set_trig_holdoff_type，仅新风格，但后续遍历产品测触发释抑时，应使用新老产品均支持的接口set_edge_trig_holdoff,其他新增接口同上。
    # ---------------------------------------------------------------------------
    def slope_string_adapter(self,slope,flag):
        """set input old->output new;get input new->output old;
        flag=True,设置适配；flag=False,获取适配"""
        Param_new = ["RISing","FALLing","ALTernate"]
        Param_old = ["POS", "NEG", "WINDOW"]#X-E POS/NEG/WINDOW,平台后期补全了，但旧指令以X-E为主
        if flag:
            index = Param_old.index(slope)
            slope = Param_new[index]
        else:
            index = Param_new.index(slope)
            slope = Param_old[index]
        return slope

    def polarity_string_adapter(self,slope,flag):
        """set input old->output new;get input new->output old;
        flag=True,设置适配；flag=False,获取适配"""
        Param_new = ["POSitive","NEGative"]
        Param_old = ["POS", "NEG"]
        if flag:
            index = Param_old.index(slope)
            slope = Param_new[index]
        else:
            index = Param_new.index(slope)
            slope = Param_old[index]
        return slope

    def couple_string_adapter(self,slope,flag):
        """set input old->output new;get input new->output old;
        flag=True,设置适配；flag=False,获取适配"""
        Param_new = ["AC","DC","LFREJect","HFREJect"]
        Param_old = ["AC", "DC", "LFREJ","HFREJ"]
        if flag:
            index = Param_old.index(slope)
            slope = Param_new[index]
        else:
            index = Param_new.index(slope)
            slope = Param_old[index]
        return slope

    def trigger_type_string_adapter(self,type,direc_flag):
        """direc_flag=Ture, set旧参->新参；false，set新参->旧参；
        """
        Param_old = ["EDGE", "SLEW", "GLIT", "TV", "WIN", "INTV", "DROP", "RUNT", "PA", "SERIAL", "QUALIFY",
                     "NEDGe", "DELay", "SHOLd", "IIC", "SPI", "UART", "CAN", "LIN", "FLEXray", "CANFd", "IIS", "M1553","SENT"]  # 此行旧指令不支持，仅为匹配new
        Param_new = ["EDGE", "SLOPe", "PULSe", "VIDeo", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "SERial",
                     "QUALified","NEDGe", "DELay", "SHOLd", "IIC", "SPI", "UART", "CAN", "LIN", "FLEXray", "CANFd", "IIS", "M1553","SENT"]
        if direc_flag:
            index = Param_old.index(type)
            type = Param_new[index]
        else:
            index = Param_new.index(type)
            if index > len(Param_old)-1:
                index = len(Param_old)-1
            type = Param_old[index]
        return type

    def trigger_limit_string_adapter(self,type,direc_flag):
        """direc_flag=Ture, set旧参->新参；false，set新参->旧参；
        """
        Param_old = ["IS","IL","I1","I2","PS","PL","P1","P2"]
        Param_new = ["LESSthan","GREATerthan","OUTer","INNer","LESSthan", "GREATerthan", "OUTer", "INNer"]
        if direc_flag:
            index = Param_old.index(type)
            type = Param_new[index]
        else:
            index = Param_new.index(type)
            type = Param_old[index]
        return type

    def trigger_droptrig_string_adapter(self,type,direc_flag):
        """direc_flag=Ture, set旧参->新参；false，set新参->旧参；
        """
        Param_old = ["STATE","EDGE"]
        Param_new = ["STATe","EDGE"]
        if direc_flag:
            index = Param_old.index(type)
            type = Param_new[index]
        else:
            index = Param_new.index(type)
            type = Param_old[index]
        return type

    def trigger_mode_string_adapter(self,type,direc_flag):
        """direc_flag=Ture, set旧参->新参；false，set新参->旧参；
        """
        Param_old = ["AUTO","NORM","SINGLE","STOP","FTRIG"]
        Param_new = ["AUTO","NORMal","SINGle","STOP","FTRIG"]
        if direc_flag:
            index = Param_old.index(type)
            type = Param_new[index]
        else:
            index = Param_new.index(type)
            type = Param_old[index]
        return type

    def set_trig_mode(self, mode):
        """设置触发模式
        mode: {AUTO,SINGLE,NORM,STOP,FTRIG}
        """
        if self.SCPI_NEW_FLAG:
            mode = self.trigger_mode_string_adapter(mode, True)
            keyword = "TRIG:MODE "
        else:
            keyword = "TRMD "
        command = keyword+ mode.upper()
        self.write(command)

    def get_trig_mode(self):
        """获取触发模式"""
        if self.SCPI_NEW_FLAG:
            keyword = "TRIG:MODE?"
            mode = self.query(keyword).rstrip()
            mode = self.trigger_mode_string_adapter(mode, False)
        else:
            keyword = "TRMD?"
            mode = self.query(keyword).rstrip()
        return mode

    def set_trig_auto(self):
        """设置触发模式为自动"""
        self.set_trig_mode("AUTO")

    def set_trig_single(self):
        """设置触发模式为单次"""
        self.set_trig_mode("SINGLE")

    def set_trig_norm(self):
        """设置触发模式为正常"""
        self.set_trig_mode("NORM")

    def set_trig_stop(self):
        """设置触发模式为停止"""
        self.set_trig_mode("STOP")

    def set_trig_type(self, trig_type, source):
        """设置触发类型及触发源
        trig_type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","SERIAL","QUALIFY","NEDGe","DELay","SHOLd"}
        source ={C1,C2,C3,C4,EX,EX5,LINE}
        """
        if self.SCPI_NEW_FLAG:
            trig_type = self.trigger_type_string_adapter(trig_type,True)
            command = "TRIG:TYPE " + trig_type
            self.write(command)
            command = "TRIG:%s:SOUR %s"%(trig_type,source)
            self.write(command)
        else:
            command = "TRSE " + trig_type.upper()+",SR,"+source.upper()
            self.write(command)

    def get_trig_type(self):
        """获取触发类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:TYPE?"
            rtn = self.query(command).rstrip("\n")
            type = self.trigger_type_string_adapter(rtn,False)
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip("\n")
            rtn = rtn.split(",")
            type = rtn[0]
        return type

    def set_trig_param_slope(self, type, slope, source="C1"):
        """设置各触发类型的斜率
		type:{EDGE, SLEW, GLIT, INTV, DROP, RUNT, QUALIFY}
		source:{CX,DX,EX,EX5,LINE}
        slope:{POS, NEG, WINDOW}"""
        if (type in ["EDGE", "SLEW","GLIT","INTV","DROP","RUNT","QUALIFY"]
                and slope in ["POS", "NEG", "WINDOW"]):
            if self.SCPI_NEW_FLAG:
                type = self.trigger_type_string_adapter(type, True)
                if type in ["GLIT","RUNT"]:
                    slope = self.polarity_string_adapter(slope, True)
                    command = "TRIG:{}:POL {}".format(type, slope)
                else:
                    slope = self.slope_string_adapter(slope, True)
                    command = "TRIG:{}:SLOP {}".format(type,slope)
                self.write(command)
            else:
                command = source.upper() + ":TRSL " + slope.upper()
                self.write(command)
            value = True
        else:
            value = False
        return value

    def get_trig_slope(self, type, source="C1"):
        """获取各触发类型斜率"""
        if type in ["EDGE", "SLEW", "GLIT", "INTV", "DROP", "RUNT", "QUALIFY"]:
            if self.SCPI_NEW_FLAG:
                type = self.trigger_type_string_adapter(type, True)
                if type in ["PULSe","RUNT"]:
                    command = "TRIG:{}:POL?".format(type)
                    slope = self.polarity_string_adapter(self.query(command).rstrip(),False)
                else:
                    command = "TRIG:{}:SLOP?".format(type)
                    slope = self.slope_string_adapter(self.query(command).rstrip(), False)
                return slope
            else:
                command = "{}:TRSL?".format(source.upper())
                return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_ex_impd(self, source, mode, impd):
        """设置EXT、EXT阻抗
        source: {EX,EX5}
        mode:{DC,AC}
        impd:{1M,50R}
        """
        command = source.upper() + ":TRCP " + mode.upper() + "," + impd.upper()
        self.write(command)

    def set_trig_coupl(self, source, mode, type="EDGE"):
        """设置触发耦合
        source:{CX,EX,EX5}
        mode:{DC,AC,LFREJ,HFREJ}
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","QUALIFY"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            mode = self.couple_string_adapter(mode,True)
            command = "TRIG:%s:COUP " % (type) + mode
        else:
            command = source.upper() + ":TRCP " + mode.upper()
        self.write(command)

    def get_trig_coupl(self, source, type="EDGE"):
        """获取触发耦合
        source:{CX,EX,EX5}
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","QUALIFY"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type,True)
            command = "TRIG:%s:COUP?" % (type)
            mode = self.query(command).rstrip()
            mode = self.couple_string_adapter(mode, False)
        else:
            command = source.upper() + ":TRCP?"
            mode = self.query(command).rstrip()
        return mode

    def set_trig_level(self,level,source,trig_type="EDGE"):
        """设置触发电平位置
        source:{CX,EX,EX5}
        trig_type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","QUALIFY","NEDG","DELay"(A)}
        """
        if self.SCPI_NEW_FLAG:
            trig_type = self.trigger_type_string_adapter(trig_type, True)
            command = "TRIG:{}:SOUR {}".format(trig_type,source)
            self.write(command)
            if trig_type in ["SLOPe","WINDow","RUNT"]:
                command = "TRIG:{}:HLEV {}".format(trig_type,level)
            elif trig_type in ["PATTern","DELay"]:
                command = "TRIG:{}:LEV {},{}".format(trig_type, source, level)
            else:
                command = "TRIG:{}:LEV {}".format(trig_type, level)
        else:
            if type(level) is str:
                command = "{}:TRLV {}".format(source,level)
            else:
                command = "{}:TRLV {}V".format(source,level)
        self.write(command)

    def get_trig_level(self, source="C1",trig_type="EDGE"):
        """获取触发电平位置
        source:{CX,EX,EX5}
        trig_type={"EDGE","SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","QUALIFY","NEDG","DELay"(A)}
        """
        if self.SCPI_NEW_FLAG:
            trig_type = self.trigger_type_string_adapter(trig_type, True)
            if trig_type in ["SLOPe","WINDow","RUNT"]:
                command = "TRIG:{}:HLEV?".format(trig_type)
            elif trig_type in ["PATTern","DELay"]:
                command = "TRIG:{}:LEV? {}".format(trig_type,source)
            else:
                command = "TRIG:{}:LEV?".format(trig_type)
        else:
            command = "{}:TRLV?".format(source)
        try:
            rcv = self.query(command).rstrip()
            if self.SCPI_NEW_FLAG and trig_type in ["PATTern"]:
                rcv = rcv.split(",")[1]
            value = float(rcv)
        except ValueError:
            value = _MEAERROR
        return value

    def set_trig_second_level(self, level, source,trig_type=None):
        """设置第二条触发电平位置
        source:{CX,EX,EX5}
        trig_type={"SLEW","WIN","RUNT","QUALIFY"}
        """
        if self.SCPI_NEW_FLAG:
            trig_type = self.trigger_type_string_adapter(trig_type, True)
            command = "TRIG:%s:SOUR %s" % (trig_type , source)
            self.write(command)
            command = "TRIG:%s:LLEV %s" % (trig_type, level)
            self.write(command)
        else:
            if type(level) is str:
                command = source.upper() + ":TRLV2 " + level.upper()
            else:
                command = source.upper() + ":TRLV2 " + str(level) + "V"
            self.write(command)

    def get_trig_second_level(self, source,type=None):
        """获取第二条触发电平位置
        source:{CX,EX,EX5}
        trig_type={"SLEW","WIN","RUNT","QUALIFY"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:%s:LLEV?" % (type)
        else:
            command = source.upper() + ":TRLV2?"
        rcv = self.query(command).rstrip()
        try:
            value = float(rcv)
        except ValueError:
            value = _MEAERROR
        return value

    def set_trig_center_level(self, level, type="WIN"):
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:%s:CLEV %s" % (type, level)
        else:
            return _SCPI_NONE
        self.write(command)

    def get_trig_center_level(self):
        if self.SCPI_NEW_FLAG:
            command = "TRIG:WIND:CLEV?"
            rcv = self.query(command).rstrip()
            try:
                value = float(rcv)
            except ValueError:
                value = _MEAERROR
            return value
        else:
            return _MEAERROR

    def set_trig_detla_level(self, level,type="WIN"):
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:%s:DLEV %s" % (type, level)
        else:
            return _SCPI_NONE
        self.write(command)

    def get_trig_detla_level(self):
        if self.SCPI_NEW_FLAG:
            command = "TRIG:WIND:DLEV?"
            rcv = self.query(command).rstrip()
            try:
                value = float(rcv)
            except ValueError:
                value = _MEAERROR
            return value
        else:
            return _MEAERROR

    def set_trig_level_to_50(self):
        """设置触发电平到波形中心
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SET50"
        else:
            command = "SET50"
        self.write(command)

    def set_pattern_trig_logic(self, logic):
        """设置码型触发逻辑
        Args:
            logic: AND,OR,NAND,NOR
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:PATT:LOG " + logic.upper()
        else:
            command = "TRPA STATE," + logic.upper()
        self.write(command)

    def get_pattern_trig_logic(self):
        """获取码型触发逻辑"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:PATT:LOG?"
            state = self.query(command).rstrip()
        else:
            command = "TRPA?"
            query=self.query(command).rstrip()
            state = query.split(",")[9]
        return state

    def set_pattern_trig_level_state(self, state_list):
        """设置码型触发电平状态
        Args:
            state_list: [X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X],C1-C4,D0-D15按序电平类型H/L/X
        """
        if self.SCPI_NEW_FLAG:
            para_str = ",".join(state_list)
            command = "TRIG:PATT:INP {}".format(para_str)
        else:
            ch_num = self.get_ch_num()
            command = "TRPA "
            for i in range(0,ch_num):
                command += "C{},{}".format(i+1, state_list[i])
                if i < ch_num-1:
                    command += ","
        self.write(command)

    def get_pattern_trig_level_state(self,source):#todo:未考虑2ch/8ch机型
        """获取码型触发源对应电平状态
        Args:
            source: C1,C2,C3,C4,D0,D1,...,D15
        """
        if re.search("C",source.upper()):
            src_index = int(source.upper().replace("C",""))-1
        elif re.search("D",source.upper()):
            src_index = int(source.upper().replace("D", ""))+4
        else:
            src_index = _MEAERROR
        if self.SCPI_NEW_FLAG:
            command = "TRIG:PATT:INP?"
            query = self.query(command).rstrip()
            state = query.split(",")
            return state[src_index]
        else:
            command = "TRPA?"
            query = self.query(command).rstrip()
            state = query.split(",")
            return state[2*src_index+1]

    def set_drop_trig_type(self, type):
        """设置超时触发类型
        type: STATE,EDGE
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_droptrig_string_adapter(type,True)
            command = "TRIG:DROP:TYPE " + type
        else:
            command = "TRDP "+type.upper()
        self.write(command)

    def get_drop_trig_type(self):
        """获取超时触发类型
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DROP:TYPE?"
            type = self.query(command).rstrip()
            state = self.trigger_droptrig_string_adapter(type, False)
        else:
            command = "TRDP?"
            state = self.query(command).rstrip()
        return state

    def set_drop_trig_time(self, time):
        """设置超时触发时间
        time:输入以s为单位,例如输入2ns：2e-09
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DROP:TIME %s" % (str(time))
        else:
            src=self.get_trig_source("DROP")
            command = "TRSE DROP,SR,{},HT,TI,HV,{}".format(src,str(time))
        self.write(command)

    def get_drop_trig_time(self):
        """获取超时触发时间"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DROP:TIME?"
            value = self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")
            value = rtn[6]
        return float(value)

    def set_trig_source(self, source,type):
        """设置触发源
        source:{CX,EX,EX5,LINE}
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:TYPE "+type.upper()
            self.write(command)
            command = "TRIG:%s:SOUR %s" % (type,source.upper())
            self.write(command)
        else:
            command = "TRSR %s,%s" %(type.upper(),source.upper())
            self.write(command)

    def get_trig_source(self, type=None):
        """获取当前触发类型的触发源
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            if type == None:
                command = "TRIG:TYPE?"
                type=self.query(command).rstrip()
            else:
                type = self.trigger_type_string_adapter(type,True)
            command = "TRIG:%s:SOUR?"% type
            rtn = self.query(command).rstrip()
        else:
            if type=="TV":
                command = "TRSE?"
                rtn = self.query(command).rstrip()
                rtn = rtn.split(",")[2]
            else:
                command = "TRSR?"
                rtn = self.query(command).rstrip()
        return rtn

    def set_trig_nosrej(self, state, type="EDGE"):
        """设置噪声抑制状态
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:%s:NREJ %s" % (type,state)
        else:
            command = "TRNR " + state.upper()
        self.write(command)

    def get_trig_nosrej(self, type=None):
        """获取噪声抑制状态
        type={"EDGE", "SLEW","GLIT","TV","WIN","INTV","DROP","RUNT","PA","NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            type = self.trigger_type_string_adapter(type, True)
            command = "TRIG:%s:NREJ?" % type
        else:
            command="TRNR?"
        return self.query(command).rstrip()

    def set_edge_trig_holdoff(self,source, ht, hv="None"):
        """设置边沿触发释抑，并设置其参数。该接口仅供平台测试边沿触发释抑时使用，其他请使用set_trig_holdoff_type
            source: {C1,C2,EX,EX5}
            ht: 保持类型，限制范围[OFF,TI]
            hv: 保持值
        """
        if self.SCPI_NEW_FLAG:
            HOLD_TYPE = {"OFF":"OFF","TI":"TIME"}
            command = "TRIG:TYPE EDGE"
            self.write(command)
            command = "TRIG:EDGE:SOUR "+source
            self.write(command)
            command = "TRIG:EDGE:HOLD " + HOLD_TYPE[ht.upper()]
            self.write(command)
            command = "TRIG:EDGE:HLDTime " + hv.upper()
            self.write(command)
        else:
            if hv == "None":
                command = ("TRSE EDGE,SR," + source.upper() + ",HT,"+ ht.upper())
            else:
                command = ("TRSE EDGE,SR," + source.upper() + ",HT," + ht.upper() + ",HV," + hv.upper())
            self.write(command)

    # ----------------------------20201215新增scpi新风格接口，入参均为新风格，旧指令需适配-------------------------------
    def video_standard_string_adapter(self,stan,flag):
        Param_old = ["NTSC", "PAL", "720P/50", "720P/60", "1080P/50", "1080P/60", "1080I/50", "1080I/60", "CUST"]
        Param_new = ["NTSC","PAL","P720L50", "P720L60" , "P1080L50",  "P1080L60", "I1080L50","I1080L60", "CUSTom"]
        if flag:
            index = Param_old.index(stan)
            stan = Param_new[index]
        else:
            index = Param_new.index(stan)
            stan = Param_old[index]
        return stan

    def set_trigger_slope(self, slope, type=None, source=None):
        """设置触发斜率,slope、type入参为新风格，set_trig_param_slope入参均未老风格
        slope = {"RISing","FALLing","ALTernate","NEGative","POSitive"}
        type = {"EDGE", "SLOPe", "PULSe", "VIDeo", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern","NEDGe","SHOLd"}
        """
        if self.SCPI_NEW_FLAG:
            if type == "PULSe" or type == "RUNT":
                command = "TRIG:%s:POL %s" % (type, slope)
            else:
                command = "TRIG:%s:SLOP %s" % (type, slope)
        else:
            if type in ["PULSe", "RUNT"]:
                slope = self.polarity_string_adapter(slope, False)
            else:
                slope = self.slope_string_adapter(slope, False)
            command = source.upper() + ":TRSL " + slope.upper()
        self.write(command)

    def get_trigger_slope(self, source, type):
        """获取触发斜率
        type = {"EDGE", "SLOPe", "PULSe", "VIDeo", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern","NEDGe","SHOLd"}
        """
        if self.SCPI_NEW_FLAG:
            if type == "PULSe" or type == "RUNT":
                command = "TRIG:%s:POL?" % (type)
                rtn = self.query(command).rstrip()
            else:
                command = "TRIG:%s:SLOP?" % (type)
                rtn = self.query(command).rstrip()
        else:
            command = source.upper() + ":TRSL?"
            slope = self.query(command).rstrip()
            if type in ["PULSe", "RUNT"]:
                rtn = self.polarity_string_adapter(slope, True)
            else:
                rtn = self.slope_string_adapter(slope, True)
        return rtn

    def set_trig_limit_type(self, type, limit):
        """设置触发限制条件
        type={SLOPe,PULSe,INTerval,RUNT,PATTern,QUALified,DELay,SHOLd}
        limit={LESSthan,GREATerthan,INNer,OUTer}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:{}:LIM {}".format(type, limit)
        else:
            if type == "PATTern":
                return #X-E类产品不支持设置limit
            type = self.trigger_type_string_adapter(type, False)
            limit = self.trigger_limit_string_adapter(limit, False)
            src = self.get_trig_source()
            #TODO:X-E分支"TRSE GLIT,SR,C2,HT,IL"不带value会死机
            temp_string = "HV,2E-6,HV2,5E-6"
            command = "TRSE {},SR,{},HT,{},{}".format(type,src,limit,temp_string)
        self.write(command)

    def get_trig_limit_type(self, type):
        """获取触发限制条件
        type = {SLOPe, PULSe, INTerval, RUNT, PATTern, QUALified, DELay，SHOLd}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:LIM?" % type
            return self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")
            if self.trigger_type_string_adapter(rtn[0],True) == type:
                limit = self.trigger_limit_string_adapter(rtn[4], True)
            else:
                limit = _SCPI_NONE
            return limit

    def set_trig_limit_upper(self, type, value):
        """设置触发限制上限值
        type = {SLOPe, PULSe, INTerval, RUNT, PATTern, QUALified，DELay，SHOLd}
        value:以“S“为单位
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:TUPP %s" % (type, str(value))
        else:
            type_old = self.trigger_type_string_adapter(type, False)
            src = self.get_trig_source()
            limit = self.get_trig_limit_type(type)
            limit_old = self.trigger_limit_string_adapter(limit, False)
            if limit == "LESSthan" :
                command = "TRSE {},SR,{},HT,{},HV,{}".format(type_old,src,limit_old,str(value))
            elif limit == "INNer" or "OUTer":
                lower = self.get_trig_limit_lower(type)
                command = "TRSE {},SR,{},HT,{},HV,{},HV2,{}".format(type_old, src, limit_old, lower,str(value))
        self.write(command)

    def get_trig_limit_upper(self, type):
        """获取触发上限值
        type = {SLOPe, PULSe, INTerval, RUNT, PATTern, QUALified, DELay，SHOLd}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:TUPP?" % type
            value = self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")
            if self.trigger_type_string_adapter(rtn[0], True) == type:
                if self.trigger_limit_string_adapter(rtn[4],True) == "LESSthan":
                    value = rtn[6]
                    value = self.value_strip_unit(value.upper(), "S")
                elif self.trigger_limit_string_adapter(rtn[4],True) == "INNer" or \
                        self.trigger_limit_string_adapter(rtn[4], True) == "OUTer":
                    value = rtn[8]
                    value = self.value_strip_unit(value.upper(), "S")
                else:
                    value = _MEAERROR
            else:
                value = _MEAERROR
        return float(value)

    def set_trig_limit_lower(self, type, value):
        """设置触发下限值
        type = {SLOPe, PULSe, INTerval, RUNT, PATTern, QUALified, DELay, SHOLd}
        value:以"S"为单位
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:TLOW %s" % (type, str(value))
        else:
            if type == "PATTern":
                command = "TRPT HT,PS,HV,{}".format(value)
            else:
                type_old = self.trigger_type_string_adapter(type, False)
                src = self.get_trig_source()
                limit = self.get_trig_limit_type(type)
                limit_old = self.trigger_limit_string_adapter(limit, False)
                if limit == "GREATerthan":
                    command = "TRSE {},SR,{},HT,{},HV,{}".format(type_old,src,limit_old,str(value))
                elif limit == "INNer" or "OUTer":
                    upper = self.get_trig_limit_upper(type)
                    command = "TRSE {},SR,{},HT,{},HV,{},HV2,{}".format(type_old, src, limit_old, str(value), upper)
        self.write(command)

    def get_trig_limit_lower(self, type):
        """获取触发下限值
        type = {SLOPe, PULSe, INTerval, RUNT, PATTern, QUALified, DELay, SHOLd}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:TLOW?" % type
            value = self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")
            if self.trigger_type_string_adapter(rtn[0], True) == type:
                if self.trigger_limit_string_adapter(rtn[4], True) == "LESSthan":
                    value = _MEAERROR
                else:
                    value = rtn[6]
                    value = self.value_strip_unit(value.upper(), "S")
            else:
                value = _MEAERROR
        return float(value)

    def set_trig_holdoff_type(self,type,holdoff):
        """设置触发释抑类型,仅供self.SCPI_NEW_FLAG=True时使用,X-E机型测试使用set_edge_trig_holdoff
         type ={"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        :holdoff_type:{OFF|EVENts|TIME}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HOLD %s"%(type,holdoff)
            self.write(command)

    def get_trig_holdoff_type(self,type):
        """获取触发释抑类型,仅供self.SCPI_NEW_FLAG=True时使用
         type = {"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
         """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HOLD?" % (type)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_holdoff_event(self,num,type):
        """设置触发释抑事件数,仅供self.SCPI_NEW_FLAG=True时使用
        type ={"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        num=1~100000000"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HLDEV %s" % (type, str(num))
            self.write(command)

    def get_trig_holdoff_event(self,type):
        """获取触发释抑事件数,仅供self.SCPI_NEW_FLAG=True时使用
         type = {"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HLDEV?" % (type)
            rtn = self.query(command).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_trig_holdoff_time(self,time,type):
        """设置触发释抑时间,仅供self.SCPI_NEW_FLAG=True时使用
         type = {"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
         time:以"s"为单位
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HLDT %s" % (type, str(time))
            self.write(command)

    def get_trig_holdoff_time(self,type):
        """获取触发释抑时间,仅供self.SCPI_NEW_FLAG=True时使用
         type = {"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HLDT?" % (type)
            rtn = self.query(command).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_trig_holdoff_start_on(self,type,start):
        """设置触发释抑计时启动条件,仅供self.SCPI_NEW_FLAG=True时使用
        type:{"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        start:["LAST_TRIG", "ACQ_START"]"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HST %s" % (type, start)
            self.write(command)

    def get_trig_holdoff_start_on(self,type):
        """获取触发释抑计时启动条件,仅供self.SCPI_NEW_FLAG=True时使用
         type ={"EDGE", "SLOPe", "PULSe", "WINDow", "INTerval", "DROPout", "RUNT", "PATTern", "NEDGe"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:HST?" % (type)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_video_trig_standard(self, standard):
        """设置视频触发标准
        <standard>:={NTSC|PAL|720P50|720P60|1080P50|1080P60|1080I50|1080I60|CUSTom}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:STAN %s" % (standard)
        else:
            standard = self.video_standard_string_adapter(standard,False)
            sync=self.get_video_trig_sync()
            sr = self.get_trig_source("TV")
            command = "TRSE TV,SR,{},STAN,{},SYNC,{}".format(sr,standard,sync)
        self.write(command)

    def get_video_trig_standard(self):
        """获取视频触发标准"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:STAN?"
            value= self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            value=rtn.split(",")[4]
            value = self.video_standard_string_adapter(value, True)
        return value

    def set_video_trig_sync(self, type):
        """设置视频触发同步类型
        sync={SELECT|ANY}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:SYNC %s" % (type)
        else:
            stand=self.get_video_trig_standard()
            sr = self.get_trig_source("TV")
            command = "TRSE TV,SR,{},STAN,{},SYNC,{}".format(sr,stand,type)
        self.write(command)

    def get_video_trig_sync(self):
        """获取视频触发同步类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:SYNC?"
            value =  self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            value=rtn.split(",")[6]
        return value.upper()

    def set_video_line(self,line):
        """设置视频触发行数
        :param line: 1~1125
        :return:
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:LINE %s" % (str(line))
        else:
            stand=self.get_video_trig_standard()
            sr = self.get_trig_source("TV")
            if stand in ["NTSC","PAL","1080I50","1080I60"]:
                stand = self.video_standard_string_adapter(stand, False)
                field =self.get_video_field()
                command = "TRSE TV,SR,{},STAN,{},SYNC,SELECT,LINE,{},FLD,{}".format(sr,stand, str(line), str(field))
            else:
                stand = self.video_standard_string_adapter(stand, False)
                command = "TRSE TV,SR,{},STAN,{},SYNC,SELECT,LINE,{}".format(sr,stand, str(line))
        self.write(command)

    def get_video_line(self):
        """获取视频触发行数"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:LINE?"
            value =  self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            value=rtn.split(",")[8]
        return float(value)

    def set_video_field(self,field):
        """设置视频触发场数
        :param line: {1,2}
        :return:
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:LINE %s" % (str(field))
        else:
            stand=self.get_video_trig_standard()
            sr = self.get_trig_source("TV")
            stand = self.video_standard_string_adapter(stand, False)
            line=self.get_video_line()
            command = "TRSE TV,SR,{},STAN,{},SYNC,SELECT,LINE,{},FLD,{}".format(sr,stand, str(line),str(field))
        self.write(command)

    def get_video_field(self):
        """获取视频触发场数"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:FIEL?"
            value =  self.query(command).rstrip()
        else:
            command = "TRSE?"
            rtn = self.query(command).rstrip()
            value=rtn.split(",")[10]
        return float(value)

    def set_video_interlace(self, interlace):
        """设置视频触发触发交错,，仅供self.SCPI_NEW_FLAG=True时使用
                interlace={"1","2","4","8"}"""
        if self.SCPI_NEW_FLAG:
            keyword = "TRIG:VID:INT "
            command = keyword + interlace.upper()
            self.write(command)

    def get_video_interlace(self):
        """获取视频触发触发交错,，仅供self.SCPI_NEW_FLAG=True时使用
                        interlace={"1","2","4","8"}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:INT?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_video_custom_filed(self, filed):
        """设置视频触发自定义下场数,，仅供self.SCPI_NEW_FLAG=True时使用
                        filed={"1","2","4","8"}"""
        if self.SCPI_NEW_FLAG:
            keyword = "TRIG:VID:FCNT "
            command = keyword + filed.upper()
            self.write(command)

    def get_video_custom_filed(self):
        """获取视频触发自定义下场数,，仅供self.SCPI_NEW_FLAG=True时使用
                        interlace={"1","2","4","8"}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:VID:FCNT?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_window_trig_type(self, win_type):
        """设置窗口触发类型,仅供self.SCPI_NEW_FLAG=True时使用
        win_type={"RELative","ABSolute"}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:WIND:TYPE %s" % (win_type)
            self.write(command)

    def get_window_trig_type(self):
        """获取窗口触发类型,仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:WIND:TYPE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_delay_trig_srca(self,state_list):
        """设置延迟触发信源A的电平状态
        Args:
            state_list: [X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X],C1-C4,D0-D15按序电平类型H/L/X
        """
        if self.SCPI_NEW_FLAG:
            para_str = ",".join(state_list)
            command = "TRIG:DEL:SOUR {}".format(para_str)
            self.write(command)

    def get_delay_trig_srca(self,source):#todo:未考虑2ch/8ch
        """获取延迟触发信源A的电平状态
        Args:
            source: C1,C2,C3,C4,D0,D1,...,D15
        """
        if re.search("C",source.upper()):
            src_index = int(source.upper().replace("C",""))-1
        elif re.search("D",source.upper()):
            src_index = int(source.upper().replace("D", ""))+4
        else:
            src_index = _MEAERROR
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:SOUR?"
            query = self.query(command).rstrip()
            state = query.split(",")
            return state[src_index]
        else:
            return _SCPI_NONE

    def set_delay_trig_srcb(self, source):
        """设置延迟触发 信源B
        Args:
            source: C1,C2,C3,C4,D0,D1,...,D15
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:SOUR2 %s" % (source)
            self.write(command)

    def get_delay_trig_srcb(self):
        """获取延迟触发 信源B"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:SOUR2?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_delay_trig_slope(self,src,slope):
        """设置延迟触发斜率
        src = {1|2},1为srcA，2为srcb
        slope = {"RISing","FALLing"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:SLOP{} {}".format(src,slope)
            self.write(command)

    def get_delay_trig_slope(self,src):
        """获取延迟触发斜率
        src = {1|2},1为srcA，2为srcb"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:SLOP{}?".format(src)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_delay_trigb_level(self,level,src=None,type=None):
        """设置延迟触发B电平
        level:单位V"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:LEV2 {}".format(level)
            self.write(command)

    def get_delay_trigb_level(self,src=None):
        """获取延迟触发B电平
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:DEL:LEV2?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_shold_trig_type(self,type):
        """设置建立/保持触发类型
         type ={"SETup", "HOLD"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:TYPE %s"%(type)
            self.write(command)

    def get_shold_trig_type(self):
        """获取建立/保持触发类型
         type ={"SETup", "HOLD"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:TYPE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_shold_trig_csource(self,source,type=None):
        """设置建立/保持触发时钟源信源
        source:{C1-C4,D0-D15}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:CS %s" %(source.upper())
            self.write(command)

    def get_shold_trig_csource(self):
        """获取建立/保持触发时钟源信源
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:CS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_shold_trig_dsource(self,source,type=None):
        """设置建立/保持触发数据源信源
        source:{C1-C4,D0-D15}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:DS %s" %(source.upper())
            self.write(command)

    def get_shold_trig_dsource(self):
        """获取建立/保持触发数据源信源
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:DS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_shold_clkthreshold(self,threshold,src=None,type=None):
        """设置建立/保持触发 时钟源阈值
        threshold:单位V"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:CTHR %s" % (str(threshold))
            self.write(command)

    def get_shold_clkthreshold(self):
        """获取建立/保持触发 时钟源阈值"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:CTHR?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_shold_datathreshold(self,threshold,src=None,type=None):
        """设置建立/保持触发 数据源阈值
        threshold:单位V"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:DTHR %s" % (str(threshold))
            self.write(command)

    def get_shold_datathreshold(self):
        """获取建立/保持触发 数据源阈值"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:DTHR?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_shold_trig_data_state(self, state):
        """设置建立/保持触发数据源的电平状态
         state =["LOW", "HIGH"]
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:LEV %s" % (state)
            self.write(command)

    def get_shold_trig_data_state(self):
        """获取建立/保持触发数据源的电平状态
         state =["LOW", "HIGH"]
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SHOL:LEV?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_nthedge_idle_time(self, times):
        """设置第N边沿的空闲时间
        times:8.00E-09~20.0"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:NEDG:IDLE %s" % (str(times))
            self.write(command)

    def get_nthedge_idle_time(self):
        """获取第N边沿的空闲时间"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:NEDG:IDLE?"
            return float(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def set_nthedge_edge_num(self, num):
        """设置第N边沿的边沿数"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:NEDG:EDGE %s" % (str(num))
            self.write(command)

    def get_nthedge_edge_num(self):
        """获取第N边沿的边沿数"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:NEDG:EDGE?"
            return float(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def set_qualified_type(self, type, option=None):
        """设置前提类型
        args:
            type:STATe、STATE_DLY、EDGE、EDGE_DLY
            option：{LOW,HIGH} when type in {STATe,STATE_DLY}
                    {RISing,FALLing} when type in {EDGE,EDGE_DLY}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:TYPE %s,%s" % (type, option)
            self.write(command)

    def get_qualified_type(self):
        """获取前提类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:TYPE?"
            rtn = self.query(command).rstrip().split(",")
            return rtn[0]
        else:
            return _SCPI_NONE

    def get_qualified_state(self):
        """获取前提状态"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:TYPE?"
            rtn = self.query(command).rstrip().split(",")
            return rtn[1]
        else:
            return _SCPI_NONE

    def set_qualified_edge_source(self,source,type=None):
        """设置前提边沿触发中边沿触发信源
        args:{Cx,Dx}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ES %s" % (source)
            self.write(command)

    def get_qualified_edge_source(self):
        """获取前提边沿触发中边沿触发信源"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ES?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_qualified_edge_level(self, level,src=None,type=None):
        """设置前提边沿触发中边沿触发电平"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ELEV %s" % (level)
            self.write(command)

    def get_qualified_edge_level(self):
        """获取前提边沿触发中边沿触发电平"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ELEV?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_qualified_edge_slope(self, slope,type=None,source=None):
        """设置前提边沿触发中边沿触发斜率
        args: {RISing,FALLing}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ESL %s" % (slope)
            self.write(command)

    def get_qualified_edge_slope(self):
        """获取前提边沿触发中边沿触发斜率"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:ESL?"
            return self.query(command)
        else:
            return _SCPI_NONE

    def set_qualified_source(self,source,type=None):
        """设置前提边沿触发中前提信源
        args:{Cx,Dx}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:QS %s" % (source)
            self.write(command)

    def get_qualified_source(self):
        """获取前提边沿触发中前提信源"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:QS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_qualified_level(self,level,src=None,type=None):
        """设置前提边沿触发中前提触发电平"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:QLEV %s" % (level)
            self.write(command)

    def get_qualified_level(self):
        """获取前提边沿触发中前提触发电平"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:QUAL:QLEV?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR
    # -----------------------------------------------------------------------------
    #
    # Measure
    #
    # ---------------------------------------------------------------------------
    # Measure封装原则：1、新增入参pos=None/"P1"
    # ---------------------------------------------------------------------------
    def stat_measure_string_adapter(self, stat, flag):
        Param_old = ["STAT1","STAT2","STAT3","STAT4","STAT5"]
        if flag:
            index = Param_old.index(stat)
            stat = str(index+1)
        else:
            stat = Param_old[int(stat)-1]
        return stat

    def set_measure_switch(self, state):
        """设置测量开关
        Args:
            state:ON,OFF
        """
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS "
        else:
            keyword = "MEASW "
        command = keyword + state.upper()
        self.write(command)

    def get_measure_switch(self):
        """获取测量开关"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS?"
        else:
            keyword = "MEASW?"
        return self.query(keyword).rstrip()

    def set_measure_mode(self, mode):
        """设置测量类型,仅self.SCPI_NEW_FLAG为True有效
        Args:
            mode:{SIMPle|ADVanced}"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:MODE "
            command = keyword + mode.upper()
            self.write(command)

    def get_measure_mode(self):
        """获取测量类型 仅self.SCPI_NEW_FLAG为True有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:MODE?"
            return self.query(keyword).rstrip()
        else:
            return _SCPI_NONE

    def set_measure_source(self, source, index=1, pos="P1"):
        """设置高级测量信源1/2，仅self.SCPI_NEW_FLAG为True有效
        source: {Cx,Zx,Fx,Dx,REFX}
        index:{1,2}
        pos={P1-P12}
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:{}:SOUR{} {}".format(pos,index,source)
            self.write(command)

    def set_measure_type(self, source, parameter, pos="P1"):
        """设置当前测量类型
        Args:
            source: {C1,C2,C3,C4,F1,F2,F3,F4},多条FUNC对应一条Math，方便兼容入参为新风格，需修改调用方
            parameter: 测量类型
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:%s:SOUR1 %s" % (pos,source.upper())
            self.write(command)
            command = "MEAS:ADV:%s:TYPE %s" % (pos,parameter.upper())
            self.write(command)
            command = "MEAS:ADV:%s ON" % (pos)
            self.write(command)
        else:
            if "F" in source.upper():
                source = "MATH"
            command = "PACU " + parameter.upper() + "," + source.upper()
            self.write(command)

    def get_measure_value(self, source, parameter, delay=None):#20201215新风格无自读数指令
        """获取指定测量类型的值，此函数对SCPI命令返回内容进行了操作
        Args:
            source: {C1,C2,C3,C4,MATH}
            parameter: 测量类型
            delay: write 和 read之间的延时,等同于超时时间
        """
        self.set_data_format(7)
        command = source.upper() + ":PAVA? " + parameter.upper()
        last = self.query(command).rstrip()
        self.set_data_format(3)
        try:
            flast = last.split(",")
            last = self.value_strip_unit(flast[1])
            flast = float(last)
        except:
            flast = _MEAERROR
        return flast

    def set_measure_delay_type(self, source, parameter, pos="P1"):
        """设置延迟类测量类型
        Args:
            source: {C1-C2, }
           parameter: 延迟类测量类型，{PHA, FRR, FRF, FFR, FFF, LRR, LRF, LFR, LFF, SKEW}
           """
        if self.SCPI_NEW_FLAG:
            delay_source = source.split("-")
            command = "MEAS:ADV:%s:SOUR1 %s" % (pos,delay_source[0])
            self.write(command)
            command = "MEAS:ADV:%s:SOUR2 %s" % (pos,delay_source[1])
            self.write(command)
            command = "MEAS:ADV:%s:TYPE %s" % (pos, parameter.upper())
            self.write(command)
            command = "MEAS:ADV:%s ON" % (pos)
            self.write(command)
        else:
            command = "MEAD {},{}".format(parameter.upper(),source.upper())
            self.write(command)

    def get_measure_delay_value(self, source , parameter,pos="P1"):#20201215新风格无自读数指令
        """获取延时类测量参数类型及其测量结果，此函数返回内容为原始返回信息
        source: {Cx-Cx}
        parameter: {PHA, FRR, FRF, FFR, FFF, LRR, LRF, LFR, LFF, SKEW}
        """
        if self.SCPI_NEW_FLAG:#规避LP8多通道bin指令不兼容
            self.set_measure_delay_type(source,parameter,pos)
            time.sleep(1)
            command = "MEAS:ADV:{}:VAL?".format(pos)
            value = self.query(command).rstrip()
        else:
            command = source.upper()+":MEAD? " + parameter.upper()
            recv = self.query(command).rstrip()
            value = recv.split(",")[1]
        if "*" in value:
            value = _MEAERROR
        return float(value)

    def clear_measure_type(self):
        """清除当前测量项"""
        if self.SCPI_NEW_FLAG:
            command = "MEAS:{}:CLE".format(self.get_measure_mode())
        else:
            # command = "PAVA CUSTALL,OFF"
            command="MEACL"
        self.write(command)

    def get_measure_pos_value(self, pos="P1"):
        """获取当前显示的第x个测量值
        pos:{P1-P12}
        """
        if self.SCPI_NEW_FLAG:
            value = self.query("MEAS:ADV:{}:VAL?".format(pos)).rstrip()
        else:
            rtn = self.query("PAVA? CUST{}".format(pos[1])).rstrip()
            rtn = rtn.split(",")
            value = rtn[2]
        try:
            value = float(value)
        except:
            if "*" in value:
                value = _MEAERROR
            else:
                value = self.value_strip_unit(rtn[2])
        return float(value)

    def set_measure_stat_state(self, state):
        """设置测量统计状态
        :param state: ON,OFF
        """
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:STAT "
        else:
            keyword = "PASTAT "
        command = keyword + state.upper()
        self.write(command)

    def get_measure_stat_state(self):
        """获取测量统计状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:STAT?"
        else:
            keyword = "PASTAT?"
        return self.query(keyword).rstrip()

    def get_measure_stat_value(self, stat, num=None):
        """获取当前显示的第stat行,num列统计值列表
        Args:
            stat:stat1,stat2,stat3,stat4,stat5
            num:0-5,分别对应current，mean，min，max，stdev，count
            num=None，返回所有统计信息
        """
        time.sleep(0.5)
        if self.SCPI_NEW_FLAG:
            index = self.stat_measure_string_adapter(stat.upper(), True)
            command = "MEAS:ADV:P{}:STAT? ALL".format(index)
            rtn = self.query(command).rstrip()
            all_value = rtn.split(",")
        else:
            command = "PAVA? {}".format(stat)
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")
            all_value = []
            for i in range(int(len(rtn)/2)):
                all_value.append(rtn[2*i+1])
        if num == None:
            for i in range(len(all_value)):
                all_value[i] = self.value_strip_unit(all_value[i])
            return all_value
        else:
            return (self.value_strip_unit(all_value[num]))

    def get_measure_stat_mean_min_max(self, stat):
        """获取当前显示的第stat行统计值:mean,min,max
        Args:
            stat:stat1,stat2,stat3,stat4,stat5
        """
        try:
            value = self.get_measure_stat_value(stat)
            return value[1], value[2], value[3]
        except:
            return _MEAERROR,_MEAERROR,_MEAERROR

    def get_measure_stat_count(self, stat):
        """获取当前显示的第stat行统计次数:count
        Args:
            stat:stat1,stat2,stat3,stat4,stat5
        """
        try:
            value = self.get_measure_stat_value(stat,5)
            return value
        except:
            return _MEAERROR

    def get_measure_stat_mean(self, stat):
        """获取当前显示的第stat行统计次数:mean
                Args:
                    stat:stat1,stat2,stat3,stat4,stat5
                """
        try:
            value = self.get_measure_stat_value(stat, 1)
            return value
        except:
            return _MEAERROR

    def get_measure_stat_reset(self):
        """重新开始统计"""
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:STAT:RES"
        else:
            command = "PASTAT RESET"
        self.write(command)

    def set_measure_gate_switch(self, state):
        """设置测量门限开关
        Args:
            state:ON,OFF
        """
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:GATE "
        else:
            keyword = "MEGS "
        command = keyword + state.upper()
        self.write(command)

    def get_measure_gate_switch(self):
        """获取测量门限开关，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:GATE?"
            rtn = self.query(keyword).rstrip()
            return rtn
        else:
            return _SCPI_NONE

    def set_measure_gateA_value(self, value):
        """设置测量门限A"""
        if self.SCPI_NEW_FLAG:
            command = "MEAS:GATE:GA {}".format(value)
        else:
            keyword = "MEGA "
            if type(value) is str:
                command = keyword + value.upper()
            else:
                command = keyword + str(value) + "S"
        self.write(command)

    def get_measure_gateA_value(self):
        """获取测量门限A，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:GATE:GA?"
            rtn = self.query(keyword).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_measure_gateB_value(self, value):
        """设置测量门限B"""
        if self.SCPI_NEW_FLAG:
            command = "MEAS:GATE:GB {}".format(value)
        else:
            keyword = "MEGB "
            if type(value) is str:
                command = keyword + value.upper()
            else:
                command = keyword + str(value) + "S"
        self.write(command)

    def get_measure_gateB_value(self):
        """获取测量门限B，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:GATE:GB?"
            rtn = self.query(keyword).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_measure_display_mode(self,mode):
        """设置测量显示模式，仅self.SCPI_NEW_FLAG为True时有效
        :param mode: {"M1","M2"}
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:STYL %s"%(mode)
            self.write(command)

    def get_measure_display_mode(self):
        """获取测量显示模式，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:STYL?"
            rtn = self.query(keyword).rstrip()
            return rtn
        else:
            return _SCPI_NONE

    def set_measure_display_line(self,line):
        """设置测量统计显示行数，仅self.SCPI_NEW_FLAG为True时有效
        :param line：1~12
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:LIN %s" % (line)
            self.write(command)

    def get_measure_display_line(self):
        """获取测量显示模式，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:LIN?"
            rtn = self.query(keyword).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_measure_max_count(self,count):
        """设置测量最大统计值
        :param count: 0~1024
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:STAT:MAXC %s" % (count)
            self.write(command)

    def get_measure_max_count(self):
        """获取测量最大统计值，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:STAT:MAXC?"
            rtn = self.query(keyword).rstrip()
            return float(rtn)
        else:
            return _MEAERROR

    def set_measure_histogram_state(self,state):
        """设置测量直方图状态
        :param state：{ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            command = "MEAS:ADV:STAT:HISTOG %s" % (state)
            self.write(command)

    def get_measure_histogram_state(self):
        """获取测量直方图状态，仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            keyword = "MEAS:ADV:STAT:HISTOG?"
            rtn = self.query(keyword).rstrip()
            return rtn
        else:
            return _SCPI_NONE

    # ------------------------此部分为扩展内容---------------------------------------
    def get_measure_vmax(self, source):
        """获取电压最大值"""
        return self.get_measure_value(source, "MAX")

    def get_measure_vmin(self, source):
        """获取电压最小值"""
        return self.get_measure_value(source, "MIN")

    def set_measure_vpp(self, source,pos="P1"):
        """设置为测量电压峰峰值"""
        self.set_measure_type(source, "PKPK",pos)

    def get_measure_vpp(self, source):
        """获取电压峰峰值"""
        return self.get_measure_value(source, "PKPK")

    def set_measure_vamp(self, source,pos="P1"):
        """设置为测量电压幅值"""
        self.set_measure_type(source, "AMPL",pos)

    def get_measure_vamp(self, source):
        """获取电压幅值"""
        return self.get_measure_value(source, "AMPL")

    def get_measure_vtop(self, source):
        """获取电压顶端值"""
        return self.get_measure_value(source, "TOP")

    def get_measure_vbase(self, source):
        """获取电压低端值"""
        return self.get_measure_value(source, "BASE")

    def get_measure_vavg(self, source):
        """获取电压周期平均值"""
        return self.get_measure_value(source, "CMEAN")

    def get_measure_mean(self, source):
        """获取电压平均值"""
        return self.get_measure_value(source, "MEAN")

    def get_measure_vrms(self, source):
        """获取电压均方根值"""
        return self.get_measure_value(source, "RMS")

    def get_measure_stedv(self, source="C1"):
        """获取测量的标准差"""
        return self.get_measure_value(source.upper(), "STDEV")

    def get_measure_period(self, source):
        """获取波形周期"""
        return self.get_measure_value(source, "PER")

    def set_measure_freq(self, source, pos="P1"):
        """设置为测量波形频率"""
        self.set_measure_type(source, "FREQ",pos)

    def get_measure_freq(self, source):
        """获取波形频率"""
        return self.get_measure_value(source, "FREQ")

    def get_measure_pwid(self, source):
        """获取正脉宽值"""
        return self.get_measure_value(source, "PWID")

    def get_measure_duty(self, source):
        """获取正占空比值"""
        return self.get_measure_value(source, "DUTY")

    def get_measure_timel(self, source="C1"):
        """"""
        return self.get_measure_value(source.upper(), "TIMEL")

    def get_measure_delay(self, source):
        """获取测量的触发延迟时间"""
        return self.get_measure_value(source.upper(), "DELAY")

    # ------------------------------------------------------------------------
    #
    # Cursor
    #
    # ------------------------------------------------------------------------
    def cursor_mode_string_adapter(self, mode, flag):
        Param_new = [["OFF"],["ON","MANual"],["ON","TRACk"],["ON","MEASure"]]
        Param_old = ["OFF","MANU","TRACK","MEASURE"]#为兼容新指令增加MEASURE
        if flag:
            index = Param_old.index(mode)
            mode = Param_new[index]
        else:
            index = Param_new.index(mode)
            mode = Param_old[index]
        return mode

    def cursor_type_string_adapter(self, state, flag):
        Param_new = ["MANual,X", "MANual,Y", "MANual,XY"]
        Param_old = ["X", "Y", "X-Y"]
        if flag:
            index = Param_old.index(state)
            mode = Param_new[index]
        else:
            index = Param_new.index(state)
            mode = Param_old[index]
        return mode

    def cursor_xy_string_adapter(self, cursor, flag):
        Param_new = ["X1","X2","Y1","Y2","X1","X2"]
        Param_old = ["HREF","HDIF","VREF","VDIF","TREF","TDIF"]
        if flag:
            index = Param_old.index(cursor)
            if index == len(Param_new):
                index = 0
            elif index == len(Param_new)+1:
                index = 1
            cursor = Param_new[index]
        else:
            index = Param_new.index(cursor)
            cursor = Param_old[index]
        return cursor

    def cursor_track_string_adapter(self,mode,direc_flag):
        """direc_flag=Ture, set旧参->新参；false，set新参->旧参；
        """
        Param_new = ["X1", "X2", "XDELta", "IXDelta", "Y1","Y2","YDELta"]
        Param_old = ["HREL", "HREL", "HREL", "HREL","VREL","VREL","VREL"]
        if direc_flag:
            index=Param_old.index(mode)
            value = Param_new[index]
        else:
            index = Param_new.index(mode)
            value = Param_old[index]
        return value
    # ----------------------------- Cursors--------------------------------
    def set_cursor_mode(self, mode):
        """设置光标模式
        Args:
            mode: {OFF,TRACK,MANU,MEASure}
        """
        if self.SCPI_NEW_FLAG:
            mode = self.cursor_mode_string_adapter(mode.upper(),True)
            command = "CURS {}".format(mode[0])
            self.write(command)
            if mode[0] == "ON":
                command = ":CURSor:MODE {}".format(mode[1])
                self.write(command)
        else:
            command = "CRMS " + mode.upper()
            self.write(command)

    def get_cursor_mode(self):
        """获取光标模式{OFF,TRACK,MANU,MEASure}"""
        if self.SCPI_NEW_FLAG:
            keyword = "CURS?"
            rtn = self.query(keyword).rstrip()
            if rtn == "ON":
                keyword = ":CURSor:MODE?"
                rtn = self.query(keyword).rstrip()
                rtn = rtn.split(",")
                mode = self.cursor_mode_string_adapter(["ON",rtn[0]],False)
            else:
                mode = rtn
        else:
            keyword = "CRMS?"
            mode = self.query(keyword).rstrip()
        return mode

    def set_cursor_type(self, type):
        """设置光标类型
        :param type: {X、Y、X-Y}"""
        if self.SCPI_NEW_FLAG:
            keyword = "CURS:MODE "
            type = self.cursor_type_string_adapter(type,True)
        else:
            keyword = "CRTY "
        command = keyword + type.upper()
        self.write(command)

    def get_cursor_type(self):
        """获取光标类型"""
        if self.SCPI_NEW_FLAG:
            keyword = "CURS:MODE?"
            rtn = self.query(keyword).rstrip()
            type = self.cursor_type_string_adapter(rtn,False)
        else:
            keyword = "CRTY?"
            type = self.query(keyword).rstrip()
        return type

    def set_cursor_set(self, source, cursor, position):
        """设置光标开启、追踪/手动模式、光标线位置
        Args:
            source: {Cx,Zx,Fx,REFx,Mx,DIGital,HISTogram}
            cursor: {HREF,HDIF,VREF,VDIF,TREF,TDIF}
            position: 0.1~15.9
        """
        if self.SCPI_NEW_FLAG:
            command = "CURS ON"
            self.write(command)
            if cursor == "HREF" or cursor == "HDIF":
                mode = "TRAC"
            else:
                mode = "MAN"
            command = "CURS:MODE {}".format(mode)
            self.write(command)
            command = "CURS:SOUR1 {}".format(source)
            self.write(command)
            command = "CURS:SOUR2 {}".format(source)
            self.write(command)
            cursor = self.cursor_xy_string_adapter(cursor,True)
            command = "CURS:{} {}".format(cursor.upper(),position)
            self.write(command)
        else:#todo:光标源未兼容
            command = "{}:CRST {},{}".format(source.upper(),cursor.upper(),position)
            self.write(command)

    def get_cursor_set(self, source, cursor):
        """获取光标设置参数
        Args:
            source: {Cx,Zx,Fx,REFx,Mx,DIGital,HISTogram}
            cursor: {HREF,HDIF,VREF,VDIF,TREF,TDIF}
            """
        if self.SCPI_NEW_FLAG:
            cursor = self.cursor_xy_string_adapter(cursor, True)
            command = "CURS:" + cursor.upper() + "?"
            try:
                data = float(self.query(command).rstrip())
            except:
                data = _MEAERROR
        else:
            command = source.upper() + ":CRST? " + cursor.upper()
            data = self.query(command).split(",")
            try:
                data = float(data[1])
            except:
                data = _MEAERROR
        return data

    # ----------------------------20201215新增scpi新风格接口，入参均为新风格，旧指令需适配-------------------------------
    def get_cursor_value(self, source, mode):
        """获取光标测量值deltaX，1/deltaX,deltaY,Y1,Y2
        Args:
            source: {C1,C2,MATH}
            mode: {XDELta,IXDelta,YDELta,Y1,Y2}
            """
        if self.SCPI_NEW_FLAG:
            command = "CURS:{}?".format(mode)
            try:
                value = float(self.query(command).rstrip())
            except:
                value = _MEAERROR
        else:
            state = self.cursor_track_string_adapter(mode, False)
            command = "{}:CRVA? {}".format(source.upper(), state)
            rcv = (self.query(command)).split(",")
            try:
                if mode == "XDELta":
                    value = float(self.value_strip_unit(rcv[1], "S"))
                elif mode == "IXDelta":
                    value = float(self.value_strip_unit(rcv[2], "Hz"))
                elif mode == "YDELta":
                    value = float(self.value_strip_unit(rcv[1], "V"))
                elif mode == "Y2":
                    value = float(self.value_strip_unit(rcv[2], "V"))
                elif mode == "Y1":
                    value = float(self.value_strip_unit(rcv[3].rstrip(), "V"))
                else:
                    value = _MEAERROR
            except:
                value = _MEAERROR
        return value

    def set_cursor_display_mode(self, type):
        """设置光标标签显示类型 仅self.SCPI_NEW_FLAG为True时有效
        type=["FOLLowing","FIXed"]
        """
        if self.SCPI_NEW_FLAG:
            command = "CURS:TAGS " + type.upper()
            self.write(command)

    def get_cursor_display_mode(self):
        """ 获取光标显示类型 仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:TAGS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_cursor_x_ref(self, type):
        """设置光标X的参考类型 仅self.SCPI_NEW_FLAG为True时有效
        type:{"DELay","POSition"}"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:XREF " + type.upper()
            self.write(command)

    def get_cursor_x_ref(self):
        """获取光标X的参考类型 仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:XREF?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_cursor_y_ref(self, type):
        """设置光标Y的参考类型 仅self.SCPI_NEW_FLAG为True时有效
        type{"OFFSet", "POSition"}"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:YREF " + type.upper()
            self.write(command)

    def get_cursor_y_ref(self):
        """获取光标Y的参考类型 仅self.SCPI_NEW_FLAG为True时有效"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:YREF?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_cursor_meas_item(self, type,srca,srcb=None):
        """设置测量光标项
        Args:
            type: {MAX,MIN,PKPK...THF}
            srca/srcb：{Cx|Zx|Fx}
        """
        if self.SCPI_NEW_FLAG:
            command = ":CURSor:MITem {},{}".format(type,srca)
            if srcb !=None:
                command = "{},{}".format(command, srcb)
            self.write(command)

    def get_cursor_meas_item(self):
        """获取测量光标项"""
        if self.SCPI_NEW_FLAG:
            command = ":CURSor:MITem?"
            rtn = self.query(command).rstrip()
            return rtn.split(",")
        else:
            return [_SCPI_NONE,_SCPI_NONE,_SCPI_NONE]

    def set_cursor_x(self, value,cur_idx=1):
        """设置光标X值"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:X{} {}".format(cur_idx,value)
            self.write(command)

    def get_cursor_x(self,cur_idx=1):
        """获取光标X值"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:X{}?".format(cur_idx)
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_cursor_source(self,source,cur_idx=1):
        """source={Cx,Zx,Fx,REFx,Mx,DIGital,HISTogram}"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:SOUR{} {}".format(cur_idx,source)
            self.write(command)

    def get_cursor_source(self,cur_idx=1):
        """source={Cx,Zx,Fx,REFx,Mx,DIGital,HISTogram}"""
        if self.SCPI_NEW_FLAG:
            command = "CURS:SOUR{}?".format(cur_idx)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    # ------------------------------------------------------------------------
    #
    # Acquire
    #
    # ------------------------------------------------------------------------
    def acq_mode_string_adapter(self,state,flag):
        """set_flag = True, 设置适配；set_flag = False, 获取适配
        """
        Param_new = ["XY","YT","ROLL"]
        Param_old = ["ON", "OFF"]
        if flag:
            index = Param_old.index(state)
            mode = Param_new[index]
        else:
            index = Param_new.index(state)
            if index > len(Param_old)-1:
                index = 1
            mode = Param_old[index]
        return mode

    def acq_way_string_adapter(self, mode, flag):
        Param_new = ["NORMal","PEAK","AVERage","ERES","HIRES"]
        Param_old = ["SAMPLING","PEAK_DETECT","AVERAGE","HIGH_RES","HIGH_RES"]
        if flag:
            index = Param_old.index(mode)
            mode = Param_new[index]
        else:
            index = Param_new.index(mode)
            mode = Param_old[index]
        return mode

    # ------------------------------------------------------------------------
    def set_memory_depth(self, depth):
        """设置存储深度"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MDEP "
        else:
            keyword = "MSIZ "
        command = keyword + depth.upper()
        self.write(command)

    def get_memory_depth_str(self):
        """获取存储深度"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MDEP?"
        else:
            keyword = "MSIZ?"
        return self.query(keyword).rstrip()

    def get_memory_depth(self):
        """获取存储深度"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MDEP?"
        else:
            keyword = "MSIZ?"
        rcv = self.query(keyword).rstrip()
        try:
            value = self.value_strip_unit(rcv)
        except:
            value = _MEAERROR
        return value

    def set_xy_mode(self, state):
        """设置XY模式
        Args:
        state: ON为XY格式，OFF为YT格式
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MODE "
            state = self.acq_mode_string_adapter(state, True)
        else:
            keyword = "XYDS "
        command = keyword + state.upper()
        self.write(command)

    def get_xy_mode(self):
        """获取XY模式状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MODE?"
            rtn = self.query(keyword).rstrip()
            state = self.acq_mode_string_adapter(rtn, False)
        else:
            keyword = "XYDS?"
            state =  self.query(keyword).rstrip()
        return state

    def set_roll_mode(self, mode):
        """设置roll模式
        mode={ON,OFF},ON:进入Roll状态，OFF:退出ROLL状态
        """
        if self.SCPI_NEW_FLAG:
            if mode.upper() == "ON":
                command = "ACQ:MODE ROLL"
            else:
                command = "ACQ:MODE YT"
        else:
            command = "ROLL " + mode.upper()
        self.write(command)

    def get_roll_mode(self):
        """获取roll模式状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:MODE?"
            rtn=self.query(keyword).rstrip()
            if rtn == "ROLL":
                state = "ON"
            else:
                state = "OFF"
        else:
            state = _SCPI_NONE
        return state

    def set_acq_way(self, way, time=None):
        """设置波形获取方式
        Args:
            way: {SAMPLING,PEAK_DETECT,AVERAGE,HIGH_RES}
            time: 平均次数,{4, 16, 32, 64,128,256}
                    或增强位数,{0.5, 1.0, 1.5, 2.0, 2.5, 3.0}
        """
        if self.SCPI_NEW_FLAG:
            way = self.acq_way_string_adapter(way.upper(),True)
            command = "ACQ:TYPE " + way
            if time:
                command = "{},{}".format(command,time)
        else:
            command = "ACQW " + way.upper()
            if time == None:
                time = 16
            if way in "AVERAGE":
                command = "{},{}".format(command, time)
            elif way in "HIGH_RES":
                self.write(command)
                command = "ACENBT " + str(time)
        self.write(command)

    def get_acq_way(self):
        """获取波形获取方式"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:TYPE?"
            rtn = self.query(keyword).rstrip()
            way = rtn.split(",")
            way = self.acq_way_string_adapter(way[0],False)
        else:
            keyword = "ACQW?"
            rtn = self.query(keyword).rstrip()
            way = rtn.split(",")
            way = way[0]
        return way

    def set_acq_stop(self):
        """在normal或auto模式下停止采集"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:STOP"
        else:
            command = "STOP"
        self.write(command)

    def set_acq_run(self):
        """Run Button，且保持上次触发模式"""
        if self.SCPI_NEW_FLAG:
            command = ":TRIG:RUN"
        else:
            command = "TRMD AUTO"#X-E无run指令，暂以AUTO模式替代
        self.write(command)

    def set_average_time(self, time):
        """设置平均次数
        Args：
            times: {4, 16, 32, 64,128,256}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:TYPE AVER,"
        else:
            keyword = "AVGA "
        command = keyword + str(time)
        self.write(command)

    def get_average_time(self):
        """获取平均次数"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:TYPE?"
            rtn = self.query(keyword).rstrip()
            value = rtn.split(",")[1]
        else:
            keyword = "AVGA?"
            value = self.query(keyword).rstrip()
        return float(value)

    def set_eres_bit(self, bit):
        """设置增强位数
        Args：
            bit: {0.5, 1.0, 1.5, 2.0, 2.5, 3.0}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:TYPE ERES,"
        else:
            keyword = "ACENBT "
        command = keyword + str(bit)
        self.write(command)

    def get_eres_bit(self):
        """获取增强位数"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:TYPE?"
            rtn = self.query(keyword).rstrip()
            value = rtn.split(",")[1]
        else:
            keyword = "ACENBT?"
            value = self.query(keyword).rstrip()
        return float(value)

    def set_acq_fast_mode(self, mode):
        """设置采集模式
        mode={FAST|SLOW}"""
        if self.SCPI_NEW_FLAG:
            command = "ACQ:AMOD " + mode
            self.write(command)

    def get_acq_fast_mode(self):
        """获取采集模式"""
        if self.SCPI_NEW_FLAG:
            command = "ACQ:AMOD?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_acq_clear_sweep(self):#TODO:X-U/2X-E/2000X-E需合入分支
        command = "ACQ:CSW"
        self.write(command)

    def set_acq_mem_mgmt(self,mode):
        """设置存储模式
        mode={AUTO|FMDepth|FSRate}"""
        if self.SCPI_NEW_FLAG:
            command = "ACQ:MMAN " + mode
            self.write(command)

    def get_acq_mem_mgmt(self):
        """获取存储模式"""
        if self.SCPI_NEW_FLAG:
            command = "ACQ:MMAN?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_acq_resolution(self, bits):
        """设置分辨率
        Args：
            bit: {8Bits,10Bits}
        """
        if self.SCPI_NEW_FLAG:
            command = "ACQ:RES " + bits
            self.write(command)

    def get_acq_resolution(self):
        """获取分辨率"""
        if self.SCPI_NEW_FLAG:
            command = "ACQ:RES?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    # ------------------------------Sequence-------------------------------
    def set_seq_mode(self, state):
        """设置sequence模式
        Args:
            state: {ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SEQ "
        else:
            keyword = "ACSQM "
        command = keyword + state.upper()
        self.write(command)

    def get_seq_mode(self):
        """获取sequence模式"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SEQ?"
        else:
            keyword = "ACSQM?"
        return self.query(keyword).rstrip()

    def set_seq_num(self, num):
        """设置sequence段数
        Args:
            num: 1~80000
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SEQ:COUN "
        else:
            keyword = "ACSQS "
        command = keyword + str(num)
        self.write(command)

    def get_seq_num(self):
        """获取sequence帧数,仅self.SCPI_NEW_FLAG为True时支持"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SEQ:COUN?"
            value = self.query(keyword).rstrip()
            return float(value)
        else:
            return _MEAERROR

    def set_interplt_way(self, way):
        """设置插值方式
        Args:
            way: ON代表正弦插值，OFF代表线性插值
        """
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:INT "
        else:
            keyword = "SXSA "
        command = keyword + way.upper()
        self.write(command)

    def get_interplt_way(self):
        """获取插值方式"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:INT?"
        else:
            keyword = "SXSA?"
        return self.query(keyword).rstrip()

    # ----------------------------SampleParameter--------------------------
    def get_wave_sample_state(self):
        """获取波形采样状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "TRIG:STAT?"
        else:
            keyword = "SAST?"
        try:
            state = self.query(keyword).rstrip()
        except:
            state = _SCPI_NONE
        return state

    def set_wave_sample_rate(self,rate):
        """设置波形采样率"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SRAT "
            command = keyword + str(rate)
            self.write(command)

    def get_wave_sample_rate(self):
        """获取波形采样率"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:SRAT?"
        else:
            keyword = "SARA?"
        rcv = self.query(keyword).rstrip()
        try:
            value = self.value_strip_unit(rcv)
        except:
            value = _MEAERROR
        return value

    def get_wave_sample_num(self):
        """获取指定通道有效采样点数"""
        if self.SCPI_NEW_FLAG:
            keyword = "ACQ:POIN?"
        else:
            keyword = "SANU? C1"
        response = self.query(keyword).rstrip()
        if not response:
            self.write_error_log("Invalid response for waveform sample number: {}".format(response))
            return

        sample_num = float(response)
        return sample_num


    # ------------------------------------------------------------------------
    #
    # WaveForm
    #
    # ------------------------------------------------------------------------
    @staticmethod
    def deal_wf_param_bin(recv):
        """解析WF参数"""
        WAVE_ARRAY_1 = recv[0x3c:0x3f + 1]
        wave_array_count = recv[0x74:0x77 + 1]
        first_point = recv[0x84:0x87 + 1]
        sp = recv[0x88:0x8b + 1]
        v_scale = recv[0x9c:0x9f + 1]
        v_offset = recv[0xa0:0xa3 + 1]
        interval = recv[0xb0:0xb3 + 1]
        code_per_div = recv[0xa4:0Xa7 + 1]  # 已进行16bit移位处理
        adc_bit = recv[0xac:0Xad + 1]
        delay = recv[0xb4:0xbb + 1]
        tdiv = recv[0x144:0x145 + 1]
        probe = recv[0x148:0x14b + 1]
        print('WAVE_ARRAY_1')
        print(WAVE_ARRAY_1)
        print('WAVE_ARRAY_2')
        data_bytes = struct.unpack("i", WAVE_ARRAY_1)[0]
        point_num = struct.unpack("i", wave_array_count)[0]
        fp = struct.unpack("i", first_point)[0]
        sp = struct.unpack("i", sp)[0]
        interval = struct.unpack("f", interval)[0]
        delay = struct.unpack("d", delay)[0]
        tdiv_index = struct.unpack("h", tdiv)[0]
        probe = struct.unpack("f", probe)[0]
        vdiv = struct.unpack("f", v_scale)[0] * probe
        offset = struct.unpack("f", v_offset)[0] * probe
        code = struct.unpack("f", code_per_div)[0]
        adc_bit = struct.unpack("h", adc_bit)[0]

        wf_param_dic = {"vdiv":vdiv,
                        "offset":offset,
                        "interval":interval,
                        "delay":delay,
                        "tdiv":tdiv_index,
                        "code":code,
                        "adc_bit":adc_bit,
                        "point":point_num}
        return wf_param_dic

    def get_wvfm_preamble(self, source):
        """获取波形参数
        source: {Cx,Fx}"""
        self.write(":WAVeform:STARt 0")
        self.write("WAV:SOUR {}".format(source))
        self.write("WAV:PREamble?")
        recv_all = self.read_raw()
        recv = recv_all[recv_all.find(b"#") + 11:]
        if len(recv)< _WF_DESC_LEN:
            print("Error:desc len less.")
        param_dic = self.deal_wf_param_bin(recv)
        return param_dic

    def set_wvfm_data(self, sp, np, fp):
        """指定返回波形中数据的数量
        Args:
            sp: 数据点间隔
            np: 传送数据点总数
            fp: 首数据点地址
        """
        if self.SCPI_NEW_FLAG:
            command = "WAV:INT {}".format(sp)
            self.write(command)
            command = "WAV:POIN {}".format(np)
            self.write(command)
            command = "WAV:STAR {}".format(fp)
            self.write(command)
        else:
            command = "WFSU SP,{},NP,{},FP,{},SN,dat2".format(sp,np,fp)
            self.write(command)

    def get_wvfm_real_data_16bit(self, source):
        """1、统一按照16bit码字返回，如ZDL-12bit.数据LSB低字节补零；
           2、X-E机型未合入WAV指令，故8bit不再补为16bit，仍按老方案转换；
        Args:
            source: {C1, C2, C3,C4,F1-F4}
            bit: 波形数据bit，如ZDL-16bit，X-E-8bit(实际12bit，但使用16bit占位)
        """
        if self.SCPI_NEW_FLAG:
            self.write(":WAVeform:WIDTh WORD")
            self.write("WAV:SOUR {}".format(source))
            points = self.get_wave_sample_num()
            one_piece_num = float(self.query(":WAVeform:MAXPoint?").strip())
            if points > one_piece_num:
                self.write(":WAVeform:POINt {}".format(one_piece_num))
            read_times = math.ceil(points / one_piece_num)
            wf_fp_cmd = ":WAVeform:STARt "
            wf_data_cmd = "WAV:DATA?"
        else:
            read_times = 1
            one_piece_num = 14E6
            wf_fp_cmd = "WFSU FP,"
            if "F" in source.upper():
                source = "MATH"
            wf_data_cmd = "{}:WF? DAT2".format(source)

        recv_all = array.array('B')  # 创建一个无符号字节类型的数组
        for i in range(0, int(read_times)):
            start = i * one_piece_num
            self.write("{}{}".format(wf_fp_cmd, start))
            self.write(wf_data_cmd)
            recv_rtn = self.read_raw()
            self.write_log('recv_rtn len={}'.format(len(recv_rtn)))
            block_start = recv_rtn.find(b"#")
            data_digit = int(recv_rtn[block_start + 1:block_start + 2])  # todo:数据块长度大于9，不可用
            data_start = block_start + 2 + data_digit
            data_len = int(recv_rtn[block_start + 2:data_start])
            self.write_log('data_start = {}, data_len={}'.format(data_start, data_len))
            recv_data = array.array('B', recv_rtn[data_start:data_start + data_len])  # 将接收到的数据直接追加到数组中
            self.write_log('recv len={}'.format(len(recv_data)))
            recv_all.extend(recv_data)  # 将接收到的数据添加到总的接收数组中
        recv_all_list = recv_all.tolist()  # 将接收数组转换为列表
        return recv_all

    def get_waveform_all(self, source):
        """
        source: {Cx,Fx,Dx}
        """
        command = "{}:WF? ALL".format(source)
        self.write(command)
    # ------------------------------------------------------------------------
    #
    # History
    #
    # ------------------------------------------------------------------------
    def history_play_string_adapter(self,state,flag):
        Param_new = ["BACKWards","PAUSe","FORWards"]
        Param_old = ["PAST","PAUSE","PRESENT"]#以X-E为主
        if flag:
            index = Param_old.index(state)
            state = Param_new[index]
        else:
            index = Param_new.index(state)
            state = Param_old[index]
        return state

    def set_history_mode(self, state):
        """设置history模式
        state: {ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR "
        else:
            keyword = "HSMD "
        command = keyword + state.upper()
        self.write(command)

    def get_history_mode(self):
        """获取history模式"""
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR?"
        else:
            keyword = "HSMD?"
        return self.query(keyword).rstrip()

    def set_history_frame(self, num):
        """设置history帧数
        num: 1~max
        """
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:FRAM "
        else:
            keyword = "FRAM "
        command = keyword + str(num)
        self.write(command)

    def get_history_frame(self):
        """获取history帧数"""
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:FRAM?"
        else:
            keyword = "FRAM?"
        return float(self.query(keyword).rstrip())

    def set_history_list(self, state):
        """设置history列表状态
        state: {ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:LIST "
        else:
            keyword = "HSLST "
        command = keyword + str(state)
        self.write(command)

    def get_history_list(self):
        """获取history列表状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:LIST?"
            rtn = self.query(keyword).rstrip()
            value = rtn.split(",")[0]
        else:
            keyword = "HSLST?"
            value = self.query(keyword).rstrip()
        return value

    def set_history_play_state(self, state):
        """设置history播放状态
        state: {BACKWards,PAUSe,FORWards}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:PLAY "
        else:
            state = self.history_play_string_adapter(state,False)
            keyword = "HSST "
        command = keyword + str(state)
        self.write(command)

    def get_history_play_state(self):
        """获取history播放状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "HISTOR:PLAY?"
            state = self.query(keyword).rstrip()
        else:
            keyword = "HSST?"
            rtn = self.query(keyword).rstrip()
            state = self.history_play_string_adapter(rtn, True)
        return state

    def set_history_list_type(self, type):
        """设置列表时间类型
        type :{TIME|DELTa}
        """
        if self.SCPI_NEW_FLAG:
            command = "HISTOR:LIST ON," + str(type)
            self.write(command)

    def get_history_list_type(self):
        """获取history列表时间类型"""
        if self.SCPI_NEW_FLAG:
            command = "HISTOR:LIST?"
            rtn = self.query(command).rstrip()
            value = rtn.split(",")
            return value[1]
        else:
            return _SCPI_NONE

    def set_history_interval(self, number):
        """设置历史列表播放间隔"""
        if self.SCPI_NEW_FLAG:
            command = "HISTOR:INTER " + str(number)
            self.write(command)

    def get_history_interval(self):
        """获取历史列表播放间隔"""
        if self.SCPI_NEW_FLAG:
            command = "HISTOR:INTER?"
            return float(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def get_history_acq_time(self):
        """获取历史列表时间戳"""
        if self.SCPI_NEW_FLAG:
            keyword = "HISTORY:TIME?"
            return self.query(keyword).rstrip()
        else:
            return _SCPI_NONE

    # ------------------------------------------------------------------------
    #
    # Search
    #
    # ------------------------------------------------------------------------
    def set_search_status(self, state):
        """设置Search开关状态
        state: {ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR " + state.upper()
            self.write(command)

    def get_search_status(self):
        """获取Search开关状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "SEAR?"
            return self.query(keyword).rstrip()
        else:
            return _SCPI_NONE

    def set_search_mode(self, mode):
        """设置搜索模式
        mode={"EDGE", "SLOPe", "PULSe", "INT", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:MODE " + mode
            self.write(command)

    def get_search_mode(self):
        """获取搜索模式"""
        if self.SCPI_NEW_FLAG:
            command = "SEAR:MODE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_search_source(self, source, mode):
        """设置搜索信源
        mode={"EDGE", "SLOPe", "PULSe", "INT", "RUNT"}
        source ={Cx}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:SOUR %s"%(mode, source)
            self.write(command)

    def get_search_source(self, mode):
        """获取搜索信源
        mode={"EDGE", "SLOPe", "PULSe", "INT", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:SOUR?" % mode
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def get_search_count(self):
        """获取搜索事件数"""
        if self.SCPI_NEW_FLAG:
            command = "SEAR:COUN?"
            return float(self.query(command))
        else:
            return _SCPI_NONE

    def get_search_event(self):
        """获取当前事件号"""
        if self.SCPI_NEW_FLAG:
            command = "SEAR:EVEN?"
            return float(self.query(command))
        else:
            return _SCPI_NONE

    def set_search_copy(self,action):
        """设置复制操作
        action = {"FROMtrigger", "TOTRigger", "CANCel"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:COPY " + action
            self.write(command)

    def set_search_slope(self, slope, mode):
        """设置各搜索模式斜率,slope、type入参为新风格
        slope = {"RISing","FALLing","ALTernate","NEGative","POSitive"}
        mode = {"EDGE", "SLOPe", "PULSe", "INTerval", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            if mode == "PULSe" or mode == "RUNT":
                command = "SEAR:%s:POL %s" % (mode, slope)
            else:
                command = "SEAR:%s:SLOP %s" % (mode, slope)
            self.write(command)

    def get_search_slope(self, mode):
        """获取各搜索模式斜率
        mode = {"EDGE", "SLOPe", "PULSe", "INTerval", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            if mode == "PULSe" or mode == "RUNT":
                command = "SEAR:%s:POL?" % (mode)
            else:
                command = "SEAR:%s:SLOP?" % (mode)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_search_level(self, level, src, mode="EDGE", state="LEV"):
        """设置各模式的搜索电平
        mode = {"EDGE", "SLOPe", "PULSe", "INTerval", "RUNT"}
        state = {"LEV", "LLEV", "HLEV"}
        """
        if self.SCPI_NEW_FLAG:
            self.set_search_source(src, mode)
            if mode in ["SLOPe","RUNT"]:
                command = "SEAR:%s:%s %s" % (mode , state, level.upper())
            else:
                if type(level) is str:
                    command = "SEAR:%s:%s %s" % (mode, state, level.upper())
                else:
                    command = "SEAR:%s:%s %s" % (mode, state, str(level)+"V")
            self.write(command)

    def get_search_level(self, src, mode="EDGE", state="LEV"):
        """获取各模式的搜索电平
        mode = {"EDGE", "SLOPe", "PULSe", "INTerval", "RUNT"}
        state = {"LEV", "LLEV", "HLEV"}
        """
        self.set_search_source(src, mode)
        if self.SCPI_NEW_FLAG:
            if mode in ["SLOPe","RUNT"]:
                command = "SEAR:%s:%s?" % (mode, state)
            else:
                command = "SEAR:%s:%s?" % (mode, state)
            return float(self.query(command))
        else:
            return _SCPI_NONE

    def set_search_limit_type(self, limit, mode):
        """设置搜索限制条件
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        limit={LESSthan,GREATerthan,INNer,OUTer}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:{}:LIM {}".format(mode, limit)
            self.write(command)

    def get_search_limit_type(self, mode):
        """获取搜索限制条件
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:LIM?" % mode
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_search_limit_upper(self, value, mode):
        """设置搜索限制上限值
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        value:以“S“为单位
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:TUPP %s" % (mode, str(value))
            self.write(command)

    def get_search_limit_upper(self, mode):
        """获取搜索上限值
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:TUPP?" % mode
            value = self.query(command).rstrip()
            return float(value)
        else:
            return _SCPI_NONE

    def set_search_limit_lower(self, value, mode):
        """设置搜索下限值
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        value:以"S"为单位
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:TLOW %s" % (mode, str(value))
            self.write(command)

    def get_search_limit_lower(self, mode):
        """获取搜索下限值
        mode = {"SLOPe", "PULSe", "INTerval", "RUNT"}
        """
        if self.SCPI_NEW_FLAG:
            command = "SEAR:%s:TLOW?" % mode
            value = self.query(command).rstrip()
            return float(value)
        else:
            return _SCPI_NONE

    # ---------------------------------------------------------------------------
    #
    # Math
    #
    # ---------------------------------------------------------------------------
    def math_oper_string_adapter(self, operate, flag):
        Param_new = ["ADD","SUBTract","MULTiply","DIVision","INTegrate","DIFF","FFT","SQRT","AVERage","ERES","IDENtity","NEGation","ABSolute","SIGN","EXP","TEN","LN","LOG","INTErpolate","MAXHold","MINHold","FILTer"]
        Param_old = ["+","-","*","/","INTG","DIFF","FFT","SQRT",
                     "AVERage","ERES","IDENtity","NEGation","ABSolute","SIGN","EXP","TEN","LN","LOG","INTErpolate","MAXHold","MINHold","FILTer"]#此行旧指令不支持，仅为匹配new
        if flag:
            index = Param_old.index(operate)
            operate = Param_new[index]
        else:
            index = Param_new.index(operate)
            operate = Param_old[index]
        return operate

    def get_math_state(self, func="FUNC1"):
        """获取数学运算开关状态"""
        if self.SCPI_NEW_FLAG:
            keyword = func + "?"
        else:
            keyword = "MTEN?"
        return self.query(keyword).rstrip()

    def set_math_state(self, state, func="FUNC1"):
        """设置数学通道开关状态
        state:{ON,OFF}"""
        if self.SCPI_NEW_FLAG:
            keyword = func
        else:
            keyword = "MTEN"
        command = "{} {}".format(keyword,state.upper())
        self.write(command)

    def set_math_operation(self, operate, source1, source2="C1", func="FUNC1"):#TODO:新风格单源算子设置bug:FUNC4:SOUR2 C1，竟然生效
        """设置数学运算算子
        :param operate: "+","-","*","/","INTG","DIFF","FFT","SQRT","AVERage","ERES","IDENtity","NEGation","ABSolute","SIGN","EXP","TEN","LN","LOG","INTErpolate","MAXHold","MINHold","FILTer"
        :param source1/2:Cx,Zx,Fx,Mx
        """
        if self.SCPI_NEW_FLAG:
            operate_new = self.math_oper_string_adapter(operate, True)
            command = func + " ON"
            self.write(command)
            command = func + ":OPER " + operate_new
            self.write(command)
            command = func+":SOUR1 " + source1
            self.write(command)
            if operate in ["+","-","*","/"]:
                command = func+":SOUR2 " + source2
                self.write(command)
        else:
            if operate in ["DIFF", "INTG", "SQRT", "FFT"]:
                command = "DEF EQN,'{}{}'".format(operate,source1.upper())
                self.write(command)
            if operate in ["+", "-", "*", "/"]:
                command = "DEF EQN,'{}{}{}'".format(source1.upper(),operate,source2.upper())
                self.write(command)

    def get_math_operation(self, func="FUNC1"):#TODO:确认返回格式，调用方看来应含算子+源，需兼容
        """获取数学运算公式,"""
        if self.SCPI_NEW_FLAG:
            command = func + ":OPER?"
            rtn = self.query(command).rstrip()
            rtn = self.math_oper_string_adapter(rtn,False)
        else:
            command = "DEF?"
            rtn = self.query(command).rstrip()
            rtn = rtn.strip("EQN,'C12")
        return rtn

    def set_math_source1(self,source,func="FUNC1"):
        """设置Math信源1
        source=C1~C4"""
        #TODO:后续功能测试需要测老机型，需补充老风格指令
        if self.SCPI_NEW_FLAG:
            command = func + ":SOUR1 " + source
        self.write(command)

    def get_math_source1(self,func="FUNC1"):
        """获取Math信源1"""
        # TODO:老风格未适配所有算子，只能取出+的src1
        if self.SCPI_NEW_FLAG:
            command = func + ":SOUR1?"
            query = self.query(command).rstrip()
        else:
            command = "DEF?"
            query_str = self.query(command).rstrip()
            rr = re.compile(r'(?<=\').*?(?=\')')
            query_source=rr.findall(query_str)[0]
            query_s=query_source.split("+")
            query=query_s[0]
        return query

    def set_math_source2(self,source,func="FUNC1"):
        """设置Math信源2"""
        # TODO:后续功能测试需要测老机型，需补充老风格指令
        if self.SCPI_NEW_FLAG:
            command = func + ":SOUR2 " + source
        self.write(command)

    def get_math_source2(self,func="FUNC1"):
        """获取Math信源1"""
        # TODO:老风格未适配所有算子，只能取出+的src2
        if self.SCPI_NEW_FLAG:
            command = func + ":SOUR2?"
            query = self.query(command).rstrip()
        else:
            command = "DEF?"
            query_str = self.query(command).rstrip()
            rr = re.compile(r'(?<=\').*?(?=\')')
            query_source=rr.findall(query_str)[0]
            query_s=query_source.split("+")
            query=query_s[1]
        return query

    def set_add_operation(self, source1, source2, func="FUNC1"):
        """设置数学运算公式为加法"""
        self.set_math_operation("+", source1, source2,func)

    def set_sub_operation(self, source1, source2, func="FUNC1"):
        """设置数学运算公式为减法"""
        self.set_math_operation("-", source1, source2,func)

    def set_fft_operation(self, source, func="FUNC1"):
        """设置数学运算公式为快速傅里叶变换"""
        self.set_math_operation("FFT", source, "C1", func)

    def set_math_vertical_pos(self, pos, func="FUNC1"):
        """设置math波形的垂直位置
        pos:新指令为电压值，旧指令为像素点
        """
        if self.SCPI_NEW_FLAG:
            keyword = func + ":POS "
        else:
            keyword = "MTVP "
        command = keyword + str(pos)
        self.write(command)

    def get_math_vertical_pos(self, func="FUNC1"):
        """获取MATH波形的垂直位置"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":POS?"
        else:
            keyword = "MTVP?"
        value =  self.query(keyword).rstrip()
        return float(value)

    def set_math_vertical_div(self, scale, func="FUNC1"):
        """设置MATH波形的垂直刻度"""
        if self.SCPI_NEW_FLAG:
            command = "{}:SCAL {}".format(func,scale)
        else:
            keyword = "MTVD "
            if type(scale) is str:
                command = keyword + scale.upper()
            else:
                command = keyword + str(scale) + "V"
        self.write(command)

    def get_math_vertical_div(self, func="FUNC1"):
        """获取math波形的垂直刻度"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":SCAL?"
        else:
            keyword = "MTVD?"
        value=self.query(keyword).rstrip()
        return float(value)

    def set_math_invert(self, mode, func="FUNC1"):
        """设置Math波形反相"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":INV "
        else:
            keyword = "MATH:INVS "
        command = keyword + mode
        self.write(command)

    def get_math_invert(self, func="FUNC1"):
        """获取Math波形反相状态"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":INV?"
        else:
            keyword = "MATH:INVS?"
        return self.query(keyword).rstrip()

    def set_intg_offset(self, offset, func="FUNC1"):
        """设置积分的偏移，仅供self.SCPI_NEW_FLAG=True时使用
        func={FUNC1,FUNC2}
        """
        if self.SCPI_NEW_FLAG:
            command = func + ":INT:OFFS " + str(offset)
            self.write(command)

    def get_intg_offset(self, func="FUNC1"):
        """获取积分偏移，仅供self.SCPI_NEW_FLAG=True时使用
        func={FUNC1,FUNC2}
        """
        if self.SCPI_NEW_FLAG:
            command = func + ":INT:OFFS?"
            value = self.query(command).rstrip()
            return float(value)
        else:
            return _SCPI_NONE

    def set_intg_gate(self, state,func="FUNC1"):
        """设置积分门限状态，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = func + ":INT:GATE " + state
            self.write(command)

    def get_intg_gate(self,func="FUNC1"):
        """获取积分门限状态，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = func + ":INT:GATE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_intg_gate_a(self, position):
        """设置积分门限A的位置，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = "FUNC:GVAL " + str(position)
            self.write(command)

    def get_intg_gate_a(self):
        """获取积分门限A的位置，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = "FUNC:GVAL?"
            rtn = self.query(command).rstrip().split(",")
            return float(rtn[0])
        else:
            return _MEAERROR

    def set_intg_gate_b(self, position):
        """设置积分门限B的位置，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            ga= self.get_intg_gate_a()
            command = "FUNC:GVAL {},{}".format(ga,position)
            self.write(command)

    def get_intg_gate_b(self):
        """获取积分门限B的位置，仅供self.SCPI_NEW_FLAG=True时使用"""
        if self.SCPI_NEW_FLAG:
            command = "FUNC:GVAL?"
            rtn = self.query(command).rstrip().split(",")
            return float(rtn[1])
        else:
            return _MEAERROR

    def set_diff_dx(self, data, func="FUNC1"):
        """设置微分的步长"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":DIFF:DX "
        else:
            keyword = "MDID "
        command = keyword + str(data)
        self.write(command)

    def get_diff_dx(self,func="FUNC1"):
        """获取微分波形步长"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":DIFF:DX?"
            value = self.query(keyword).rstrip()
            return float(value)
        else:
            return _MEAERROR

    def set_math_average_num(self, num, func="FUNC1"):
        """设置平均算子的平均次数"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":AVERage:NUM "
            command = keyword + str(num)
            self.write(command)

    def set_math_eres_bit(self, num, func="FUNC1"):
        """设置ERES算子的Bit位数"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":ERES:BITS "
            command = keyword + str(num)
            self.write(command)

    def set_math_minmaxhold_sweep(self, oper, num, func="FUNC1"):
        """设置保持算子的最大限制
        oper={MAXHold|MINHold}
        num=[0,2147483646],0表示Unlimited"""
        if self.SCPI_NEW_FLAG:
            command = "{}:{}:SWeeps {}".format(func,oper,num)
            self.write(command)

    def set_math_interpolate_coef(self, num, func="FUNC1"):
        """设置插值算子的倍数
        num=[2,5,10,20]"""
        if self.SCPI_NEW_FLAG:
            command = "{}:INTE:COEF {}".format(func,num)
            self.write(command)

    # --------------------------------MathFFT------------------------------------
    def fft_window_string_adapter(self, window, flag):
        Param_new = ["RECTangle","BLACkman","HANNing","HAMMing","FLATtop"]
        Param_old = ["RECT","BLAC","HANN","HAMM","FLATTOP"]
        if flag:
            index = Param_old.index(window)
            window = Param_new[index]
        else:
            index = Param_new.index(window)
            window = Param_old[index]
        return window

    def fft_unit_string_adapter(self, window, flag):
        Param_new = ["Vrms","DBm","DBVrms"]
        Param_old = ["VRMS","DBM","DBVRMS"]
        if flag:
            index = Param_old.index(window)
            window = Param_new[index]
        else:
            index = Param_new.index(window)
            window = Param_old[index]
        return window

    def set_fft_auto(self, type=None,func="FUNC1"):
        """FFT自动设置，仅self.SCPI_NEW_FLAG为True时使用
        type = [NORM,PEAK,SPAN],
        func = [FUNC1,FUNC2,FUNC3,FUNC4]
        """
        if self.SCPI_NEW_FLAG:
            if type == None:
                keyword = "{}:FFT:AUT".format(func)
            else:
                keyword = "{}:FFT:AUT {}".format(func,type)
            self.write(keyword)

    def set_fft_window(self, window, func="FUNC1"):
        """
        设置FFT窗口类型
        :param window: "RECT","BLAC","HANN","HAMM","FLATTOP"
        """
        if self.SCPI_NEW_FLAG:
            window=self.fft_window_string_adapter(window,True)
            keyword = func + ":FFT:WIND "
        else:
            keyword = "FFTW "
        command = keyword + window.upper()
        self.write(command)

    def get_fft_window(self, func="FUNC1"):
        """获取FFT窗口类型"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:WIND?"
            window = self.query(keyword).rstrip()
            window = self.fft_window_string_adapter(window, False)
        else:
            keyword = "FFTW?"
            window = self.query(keyword).rstrip()
        return window.upper()

    def set_fft_vertical_scale(self, scale, func="FUNC1"):
        """设置FFT垂直档位 """
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:SCAL "
        else:
            keyword = "FFTS "
        command = keyword + str(scale)
        self.write(command)

    def get_fft_vertical_scale(self, func="FUNC1"):
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:SCAL?"
            value = self.query(keyword).rstrip()
        else:
            keyword = "FFTS?"
            value = self.query(keyword).rstrip()
            value = self.value_strip_unit(value)
        return float(value)

    def math_fft_string_adapter(self, mode, flag):
        Param_new = ["SPLit", "FULL", "EXCLusive"]
        Param_old = ["OFF", "ON", "EXCLU"]
        if flag:
            index = Param_old.index(mode)
            operate = Param_new[index]
        else:
            index = Param_new.index(mode)
            operate = Param_old[index]
        return operate

    def set_fft_display_state(self, display):
        """设置FFT显示类型
        display: SPLit,FULL, EXCLusive
        """
        if self.SCPI_NEW_FLAG:
            keyword = "FUNC:FFTD "
        else:
            display = self.math_fft_string_adapter(display, False)
            keyword = "FFTF "
        command = keyword + display.upper()
        self.write(command)

    def get_fft_display_state(self):
        """获取FFT显示类型"""
        if self.SCPI_NEW_FLAG:
            keyword = "FUNC:FFTD?"
            rtn = self.query(keyword).rstrip()
        else:
            keyword = "FFTF?"
            rtn = self.query(keyword).rstrip()
            rtn = self.math_fft_string_adapter(rtn, False)
        return rtn

    def set_fft_ref_level(self, ver_ref_level, func="FUNC1"):
        """设置FFT垂直位移"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:RLEV "
        else:
            keyword = "FFTP "
        command = keyword + str(ver_ref_level)
        self.write(command)

    def get_fft_ref_level(self, func="FUNC1"):
        """获取FFT垂直位移"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:RLEV?"
            value = self.query(keyword).rstrip()
        else:
            keyword = "FFTP?"
            value = self.query(keyword).rstrip()
            value = self.value_strip_unit(value)
        return float(value)

    def set_fft_vertical_units(self,unit, func="FUNC1"):
        """设置FFT垂直单位
        unit:{VRMS,DBM,DBVRMS}"""
        if self.SCPI_NEW_FLAG:
            unit = self.fft_unit_string_adapter(unit, True)
            keyword = func + ":FFT:UNIT "
        else:
            keyword = "FFTU "
        command = keyword + str(unit)
        self.write(command)

    def get_fft_vertical_units(self, func="FUNC1"):
        """获取FFT垂直单位"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:UNIT?"
            unit =  self.query(keyword).rstrip()
            unit = self.fft_unit_string_adapter(unit, False)
        else:
            keyword = "FFTU?"
            unit = self.query(keyword).rstrip()
        return unit

    def set_fft_load(self, load,func="FUNC1"):
        """设置FFT外部负载
        load:1~1000000"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:LOAD "+str(load)
        else:
            keyword = "FFTL "+str(load)
        self.write(keyword)

    def get_fft_load(self, func="FUNC1"):
        """获取FFT外部负载"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:LOAD?"
        else:
            keyword = "FFTL?"
        return float(self.query(keyword).rstrip())

    def set_fft_horizontal_center(self, horiz_center, func="FUNC1"):
        """设置FFT中心位置"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:HCEN "
        else:
            keyword = "FFTC "
        command = keyword + str(horiz_center)
        self.write(command)

    def get_fft_horizontal_center(self, func="FUNC1"):
        """获取FFT中心位置"""
        if self.SCPI_NEW_FLAG:
            keyword = func + ":FFT:HCEN?"
        else:
            keyword = "FFTC?"
        value = self.query(keyword).rstrip()
        value = self.value_strip_unit(value)
        return value

    def get_fft_horizontal_scale(self, func="FUNC1"):
        """获取FFT水平档位"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:HSC?"
        else:
            command = "FFTT?"
        value = self.query(command).rstrip()
        value = self.value_strip_unit(value)
        return value

    def set_fft_span(self, span, func="FUNC1"):
        """设置FFT水平范围"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SPAN " + str(span)
            self.write(command)

    def get_fft_span(self, func="FUNC1"):
        """获取FFT水平范围"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SPAN?"
            value = self.query(command).rstrip()
            return float(value)
        else:
            return _MEAERROR

    def set_fft_max_point(self, point, func="FUNC1"):
        """设置FFT最大点数"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:POIN " + point
            self.write(command)

    def get_fft_max_point(self, func="FUNC1"):
        """获取FFT最大点数"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:POIN?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_fft_mode(self, mode, func="FUNC1"):
        """设置FFT模式
        mode:{NORMal|MAXHold|AVERage[,num]}
        """
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:MODE " + mode
            self.write(command)

    def get_fft_mode(self, func="FUNC1"):
        """获取FFT模式"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:MODE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_fft_reset(self, func="FUNC1"):
        """重置FFT"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:RESET"
            self.write(command)

    def set_fft_tool_type(self, type, func="FUNC1"):
        """设置FFT搜索工具类型
        type:{OFF|PEAK|MARKer}
        """
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR " + type
            self.write(command)

    def get_fft_tool_type(self, func="FUNC1"):
        """获取FFT搜索工具类型"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_fft_search_threshold(self, value, func="FUNC1"):
        """设置峰值阈值"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR:THR " + str(value)
            self.write(command)

    def get_fft_search_threshold(self, func="FUNC1"):
        """获取峰值阈值"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR:THR?"
            value = self.query(command).rstrip()
        else:
            value = _MEAERROR
        return float(value)

    def set_fft_search_excursion(self, value, func="FUNC1"):
        """设置峰值偏移值"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR:EXC " + str(value)
            self.write(command)

    def get_fft_search_excursion(self, func="FUNC1"):
        """获取峰值偏移值"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR:EXC?"
            value = self.query(command).rstrip()
        else:
            value = _MEAERROR
        return float(value)

    def set_fft_search_marker_freq(self,num,freq,func="FUNC1"):
        """设置fft marker位置"""
        if self.SCPI_NEW_FLAG:
            command = "{}:FFT:SEARch:MARKer{} {}".format(func,num,freq)
            self.write(command)

    def get_fft_search_result(self, func="FUNC1"):
        """获取搜索结果"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:SEAR:RES?"
            rtn = self.query(command).rstrip()
            peak_list = rtn.split(";")
            peak_list.pop()
        else:
            peak_list = []
        return peak_list

    def get_fft_sample_info(self, func="FUNC1"):
        """获取FFT采样率、当前点数、采样间隔、平均计数"""
        if self.SCPI_NEW_FLAG:
            command = func + ":FFT:INF?"
            rtn = self.query(command).rstrip()
            info_list = rtn.split(",")
        else:
            info_list = []
        return info_list

    def set_math_label_state(self, state, func="FUNC1"):
        """设置数学通道标签状态"""
        if self.SCPI_NEW_FLAG:
            command = func + ":LAB " + state
            self.write(command)

    def get_math_label_state(self, func="FUNC1"):
        """获取数学通道标签状态"""
        if self.SCPI_NEW_FLAG:
            command = func+":LAB?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_math_label_text(self, txt,func="FUNC1"):
        """设置数学通道开关文本"""
        if self.SCPI_NEW_FLAG:
            command = func + ":LAB:TEXT \"%s\"" % txt
            self.write(command)

    def get_math_label_text(self, func="FUNC1"):
        """获取数学通道标签文本"""
        if self.SCPI_NEW_FLAG:
            command = func + ":LAB:TEXT?"
            rtn = self.query(command).rstrip()
            return  rtn.strip("\"")
        else:
            return _SCPI_NONE

    # ------------------------------------------------------------------------
    #
    # DefaultSetup
    #
    # ------------------------------------------------------------------------
    def set_default_state(self):
        """恢复出厂设置，使命令返回信息格式只有结果"""
        # self.query("ALST? ")
        self.write("*RST")
        flag = self.get_reg_opc()
        time.sleep(10)#待状态稳定，再进行下一步操作，避免配置不生效(如autoset)

    # -----------------------------------------------------------------------
    #
    # Display
    #
    # -----------------------------------------------------------------------
    def display_type_string_adapter(self, state, flag):
        Param_new=["DOT","VECTor"]
        Param_old=["ON","OFF"]
        if flag:
            index = Param_old.index(state)
            mode= Param_new[index]
        else:
            index = Param_new.index(state)
            mode= Param_old[index]
        return  mode

    def persist_time_string_adapter(self, time, flag):
        Param_new = ["OFF","INFinite","1S","5S","10S","30S"]
        Param_old = ["OFF", "INFINITE", "1", "5", "10", "30"]
        if flag:
            index = Param_old.index(time)
            time = Param_new[index]
        else:
            index = Param_new.index(time)
            time = Param_old[index]
        return time

    def display_grid_string_adapter(self,mode,flag):
        Param_new = ["FULL","LIGHt","NONE"]
        Param_old = ["FULL","HALF","OFF"]
        if flag:
            index = Param_old.index(mode)
            mode = Param_new[index]
        else:
            index = Param_new.index(mode)
            mode = Param_old[index]
        return  mode

    # -----------------------------------------------------------------
    def set_display_type(self, state):
        """设置显示方式为矢量或点显，
            Args:
                state: OFF状态为矢量，ON状态为点显
        """
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:TYPE "
            state = self.display_type_string_adapter(state,True)
        else:
            keyword = "DTJN "
        command = keyword + state.upper()
        self.write(command)

    def get_display_type(self):
        """获取显示方式，ON代表矢量，OFF代表点显"""
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:TYPE?"
            rtn = self.query(keyword).rstrip()
            type = self.display_type_string_adapter(rtn,False)
        else:
            keyword = "DTJN?"
            type = self.query(keyword).rstrip()
        return type

    def set_color_grade(self, state):
        """设置色温状态,仅供self.SCPI_NEW_FLAG=False时使用
        state:{ON,OFF}"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:COL " + state.upper()
            self.write(command)

    def get_color_grade(self):
        if self.SCPI_NEW_FLAG:
            command = "DISP:COL?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_display_backlight(self, light):
        """设置背光亮度,仅供self.SCPI_NEW_FLAG=False时使用"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:BACK " + str(light)
            self.write(command)

    def get_display_backlight(self):
        """获取背光亮度值"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:BACK?"
            value = self.query(command).rstrip()
            return float(value)
        else:
            return _SCPI_NONE

    def set_grid_type(self, param):
        """设置网格类型
        Args:
            param:网格类型（FULL,HALF,OFF）
        """
        if self.SCPI_NEW_FLAG:
            param= self.display_grid_string_adapter(param,True)
            keyword = "DISP:GRID "
        else:
            keyword = "GRDS "
        command = keyword + param.upper()
        self.write(command)

    def get_grid_type(self):
        """获取网格类型"""
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:GRID?"
            rtn = self.query(keyword).rstrip()
            rtn = self.display_grid_string_adapter(rtn, False)
        else:
            keyword = "GRDS?"
            rtn = self.query(keyword).rstrip()
        return rtn

    def set_trace_gride_intensity(self, value1, value2):
        """设置波形和网格亮度
        Args:
            value1: 波形亮度值（30~100）
            value2: 网格亮度值（30~100）
            """
        if self.SCPI_NEW_FLAG:
            command1 = "DISP:INT "+str(value1)
            command2 = "DISP:GRAT "+str(value2)
            self.write(command1)
            self.write(command2)
        else:
            command = "INTS GRID," + str(value1) + ",TRACE," + str(value2)
            self.write(command)

    def get_trace_gride_intensity(self):
        """获取波形和网格亮度值"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:INT?"
            rtn_int = self.query(command).rstrip()
            command = "DISP:GRAT?"
            rtn_grad = self.query(command).rstrip()
        else:
            command = "INTS?"
            rtn = self.query(command).rstrip()
            rtn_int = rtn.split(",")[1]
            rtn_grad = rtn.split(",")[3]
        return float(rtn_int),float(rtn_grad)

    def set_persist_time(self, time):
        """设置持续显示时间
        Args:
            time: 持续时间/s{OFF,1,5,10,30,INFINITE}
        """
        if self.SCPI_NEW_FLAG:
            time = self.persist_time_string_adapter(time,True)
            keyword = "DISP:PERS "
        else:
            keyword = "PESU "
        command = keyword + time.upper()
        self.write(command)

    def get_persist_time(self):
        """获取持续显示时间"""
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:PERS?"
            rtn = self.query(keyword).rstrip()
            time = self.persist_time_string_adapter(rtn,False)
        else:
            keyword = "PESU?"
            time = self.query(keyword).strip()
        return time

    def set_display_clear(self):
        """清除显示"""
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:CLE"
        else:
            keyword = "DSCL"
        self.write(keyword)

    def set_menu_style(self,style):
        """设置菜单样式
        style:{EMBedded,FLOating}"""
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:MENU {}".format(style)
            self.write(keyword)

    def get_menu_style(self):
        """获取菜单样式"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:MENU?"
            value = self.query(command).rstrip()
            return value
        else:
            return _SCPI_NONE

    def set_menu_autohide(self,hide):
        """设置菜单隐藏时间
        hide :{OFF,3S,5S,10,30S,60S}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "DISP:MENU:HIDE {}".format(hide)
            self.write(keyword)

    def get_menu_autohide(self):
        """获取菜单隐藏时间"""
        if self.SCPI_NEW_FLAG:
            command = "DISP:MENU:HIDE?"
            value = self.query(command).rstrip()
            return value
        else:
            return _SCPI_NONE

    # --------------------------------------------------------------------------
    #
    # RefWav
    #
    # --------------------------------------------------------------------------
    # Ref新指令上风格完全不同，旧接口调用方仅用作保存Ref，需要注意处理set_ref_save
    # --------------------------------------------------------------------------
    def set_ref_sr(self, trace):#20201215 多条FUNC对应一条Math，方便兼容入参为新风格，需修改调用方
        """设置参考信源
        trace = [C1,C2,C3...,D15,F1,F2,F3,F4]
        """
        if self.SCPI_NEW_FLAG:
            self.ref_src = trace
        else:
            if "F" in trace.upper():
                trace = "MATH"
            command = "REFSR " + trace.upper()
            self.write(command)

    def get_ref_sr(self):
        """获取参考信源"""
        if self.SCPI_NEW_FLAG:
            return _SCPI_NONE
        else:
            command = "REFSR?"
            return self.query(command).rstrip()

    def set_ref_location(self, ref):
        """设置参考波形存储位置
        Args:
             ref: {REFA,REFB}
        """
        self.ref_location = _SCPI_NONE
        if self.SCPI_NEW_FLAG:
            self.ref_location = ref
        else:
            command = "REFLA " + ref.upper()
            self.write(command)

    def get_ref_location(self):
        """获取参考波形存储位置"""
        if self.SCPI_NEW_FLAG:
            return _SCPI_NONE
        else:
            command = "REFLA?"
            return self.query(command).rstrip()

    def set_ref_save(self):
        """存储参考波形"""
        if self.SCPI_NEW_FLAG:
            command = "{}:DATA SAVE,{}".format(self.ref_location, self.ref_src)
        else:
            command = "REFSA"
        self.write(command)
        flag = self.get_reg_opc()
        time.sleep(1)#ref存储到显示需要时间

    def set_ref_display(self, state):
        """设置当前激活参考波形显示状态
        Args:
             state: {ON,OFF}
        """
        Param_old = ["ON","OFF"]
        Param_new = ["LOAD","UNLoad","SAVE"]
        if self.SCPI_NEW_FLAG:
            state = Param_new[Param_old.index(state.upper())]
            try:
                location = self.ref_location
            except:
                location = "REFA"
            command = "{}:DATA {}".format(location, state)
        else:
            command = "REFDS " + state.upper()
        self.write(command)
        flag = self.get_reg_opc()

    def get_ref_display(self):
        """获取当前激活参考波形显示状态"""
        if not self.SCPI_NEW_FLAG:
            command = "REFDS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_refwav(self, trace, ref, state):
        """设置参考波形
        Args:
            trace: {C1,C2,C3,C4,D0....D15,F1,F2,F3,F4}
             ref: {REFA,REFB,REFC,REFD}
             state: {ON,OFF}
        """
        self.set_ref_sr(trace)
        time.sleep(0.2)
        self.set_ref_location(ref)
        time.sleep(0.2)
        self.set_ref_save()
        self.set_ref_display(state)

    def set_ref_offset(self, offset):
        """设置参考波形垂直位置"""
        if self.SCPI_NEW_FLAG:
            command = "{}:DATA:POS {}".format(self.ref_location,offset)
        else:
            if type(offset) is str:
                command = "REFPO " + offset.upper()
            else:
                command = "REFPO " + str(offset) + "V"
        self.write(command)

    def get_ref_offset(self):
        """查询参考波形垂直位置"""
        if self.SCPI_NEW_FLAG:
            command = "{}:DATA:POS?".format(self.ref_location)
        else:
            command = "REFPO?"
        recv = self.query(command).rstrip()
        value = self.value_strip_unit(recv,"V")
        return value

    def set_ref_scale(self,scale):
        """设置参考波形垂直档位"""
        if self.SCPI_NEW_FLAG:
            command = "{}:DATA:SCAL {}".format(self.ref_location,scale)
        else:
            command = "REFSC " + str(scale)
        self.write(command)

    def get_ref_scale(self):
        """获取参考波形垂直档位"""
        if self.SCPI_NEW_FLAG:
            command = "{}:DATA:SCAL?".format(self.ref_location)
        else:
            command = "REFSC?"
        recv = self.query(command).rstrip()
        value = self.value_strip_unit(recv, "V")
        return value

    def set_ref_label_state(self, ref, state):
        """设置参考波形标签状态"""
        if self.SCPI_NEW_FLAG:
            command = ref + ":LAB " + state
            self.write(command)

    def get_ref_label_state(self,ref):
        """获取参考波形标签状态"""
        if self.SCPI_NEW_FLAG:
            command = ref + ":LAB?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_ref_label_text(self, ref, text):
        """设置参考波形标签状态文本"""
        if self.SCPI_NEW_FLAG:
            command = ref + ":LAB:TEXT \"%s\""%text
            self.write(command)

    def get_ref_label_text(self,ref):
        """获取参考波形标签状态文本"""
        if self.SCPI_NEW_FLAG:
            command = ref + ":LAB:TEXT?"
            rtn = self.query(command).rstrip()
            return  rtn.strip("\"")
        else:
            return _SCPI_NONE

    # -------------------------------------------------------------------------
    #
    # Print
    #
    # -------------------------------------------------------------------------
    def set_print(self, psize, isize, format, bckg, prtkey):
        """设置打印参数"""
        command = ("HCSU PSIZE," + psize.upper() + ",ISIZE," + isize.upper() + ",FORMAT,"
                   + format.upper() + ",BCKG," + bckg.upper() + ",PRTKRY," + prtkey.upper())
        self.write(command)

    def get_print(self):
        """获取打印参数"""
        command = "HCSU?"
        return self.query(command)

    # ---------------------------------------------------------------------------
    #
    # Save
    #
    # ---------------------------------------------------------------------------
    def save_ref_external(self, path, source):
        """ 存储通道波形到外部"""
        if self.SCPI_NEW_FLAG:
            command = "SAVE:REF \"%s\",%s" % (path, source)
            self.write(command)
        flag = self.get_reg_opc()

    def recall_ref_external(self, path, ref):
        """path="{local|net_storage|U-disk}/filename",
        ref={REFx}"""
        if self.SCPI_NEW_FLAG:
            command = "REC:REF %s,\"%s\"" % (ref, path)
            self.write(command)
        flag = self.get_reg_opc()

    def save_image_external(self, path, type, invert="OFF"):
        """存储图片
        path="{local|net_storage|U-disk}/filename",
        type={BMP|JPG|PNG},invert={ON|OFF}"""
        if self.SCPI_NEW_FLAG:
            command = "SAVE:IMAG \"%s\",%s,%s" % (path, type, invert)
            self.write(command)
        flag = self.get_reg_opc()

    def save_binary_external(self, path,source):
        """存储二进制文件"""
        if self.SCPI_NEW_FLAG:
            command = "SAVE:BIN \"%s\",%s" % (path, source)
            self.write(command)
        flag = self.get_reg_opc()

    def save_csv_external(self, path, source, head="ON"):
        """存储CSV文件
            path:"string",self.SCPI_NEW_FLAG=True时有效
            src:{Cx,Fx,Zx,D0_D15,DIGital,ALL},self.SCPI_NEW_FLAG=True时有效
            head:{ON，OFF}，选择是否保存参数"""
        if self.SCPI_NEW_FLAG:
            command = "SAVE:CSV \"%s\",%s,%s" % (path, source, head)
        else:
            command = "CSVS {}".format(head.upper())
        self.write(command)
        flag = self.get_reg_opc()

    def save_matlab_external(self, path, source):
        """存储MATlab文件"""
        if self.SCPI_NEW_FLAG:
            command = "SAVE:MATL \"%s\",%s" % (path, source)
        self.write(command)
        flag = self.get_reg_opc()

    def save_setup(self, path_type, path):
        """存储SetUp(xml文件)
        path_type: INT, EXT
        path: INT:1~20, EXT:外部储存路径,
        self.SCPI_NEW_FLAG=true,以“.xml”结尾的字符串，可包含“/”
        self.SCPI_NEW_FLAG=false,以“.SET”结尾的八位以内字符串，可包含“/”
        """
        if self.SCPI_NEW_FLAG:
            if path_type == "INT":
                command = "SAVE:SET INT,{}".format(path)
            else:
                command = "SAVE:SET EXT,\"{}\"".format(path)
        else:
            if path_type=="INT":
                command = "*SAV {}".format(path)
            else:
                command = "STPN DISK,UDSK,FILE,\"{}\"".format(path)
        self.write(command)
        flag = self.get_reg_opc()

    def save_default_key(self,type="CUSTom"):
        """设置默认设置
        type={FACTory,CUSTom}"""
        if self.SCPI_NEW_FLAG:
            command = ":SAVE:DEFault {}".format(type)
        else:
            command = "DFKS"
        self.write(command)
        time.sleep(5)
        flag = self.get_reg_opc()

    def recall_setup(self, path_type, path):
        """调用Setup(xml文件)
        :arg
        path_type: {INT, EXT}
        path: INT:1~20,EXT:外部储存路径
        self.SCPI_NEW_FLAG=true,以“.xml”结尾的字符串，可包含“/”
        self.SCPI_NEW_FLAG=false,以“.SET”结尾的八位以内字符串，可包含“/”
        """
        if self.SCPI_NEW_FLAG:
            if path_type == "INT":
                command = ":REC:SET INT,{}".format(path)
            else:
                command = ":REC:SET EXT,\"{}\"".format(path)
        else:
            if path_type == "INT":
                command = "*RCL " + str(path)
            else:
                command = "RCPN DISK,UDSK,FILE,\"{}\"".format(path)
        self.write(command)
        flag = self.get_reg_opc()
        time.sleep(10)#todo:ui更新太慢

    def recall_erase(self):
        """安全擦除"""
        if self.SCPI_NEW_FLAG:
            command = "REC:SER"
            self.write(command)
            flag = self.get_reg_opc()

    def recall_factory_setup(self):
        if self.SCPI_NEW_FLAG:
            command = "REC:FDEF"
            self.write(command)
            time.sleep(10)
            flag = self.get_reg_opc()

    # -----------------------------------PanelSetup------------------------------
    def get_setup_data(self):
        """获取面板设置,返回形式为xml文件，仅self.SCPI_NEW_FLAG=False时使用"""
        if not self.SCPI_NEW_FLAG:
            command = "PNSU?"
            self.write(command)
            return self.read_raw()
        else:
            return _SCPI_NONE

    def set_setup_data_from_ext(self,file):
        """将面板设置从外部调出，仅self.SCPI_NEW_FLAG=False时使用
        Args:
            file: 通过PNSU？命令获取的面板设置存的文件
        """
        #TODO:当前新风格指令测试需要用到
        #if not self.SCPI_NEW_FLAG:
        f = open(file,"r")
        setup = f.read()
        f.close()
        command = "PNSU " + setup
        self.write(command)
        time.sleep(5)

    def set_netstorage_param(self,path,user="",pwd="",anon=0,auto_con=0,
                             rem_path=1,rem_user=0,rem_pwd=0):
        """path,user,pwd=Quoted string,""
        anon,auto_con,rem_path,rem_user,rem_pwd={0|1}"""
        if self.SCPI_NEW_FLAG:
            command = "SYST:NST \"{}\",\"{}\",\"{}\",{},{},{},{},{}".format(path,user,pwd,anon,auto_con, \
                                                                            rem_path,rem_user,rem_pwd)
            self.write(command)

    def set_netstorage_connect(self,oper):
        """oper={CONNect|DISConnect}"""
        if self.SCPI_NEW_FLAG:
            command = "SYST:NST:{}".format(oper)
            self.write(command)

    def get_netstorage_state(self):
        if self.SCPI_NEW_FLAG:
            command = "SYST:NST:STAT?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    # -----------------------------------------------------------------
    #
    # Utility
    #
    # -----------------------------------------------------------------
    def set_buzz_state(self, state):
        """设置蜂鸣器状态
        Args:
            state: {ON,OFF}
        """
        if self.SCPI_NEW_FLAG:
            keyword = "SYST:BUZZ "
        else:
            keyword = "BUZZ "
        command = keyword + state.upper()
        self.write(command)

    def get_buzz_state(self):
        """获取蜂鸣器状态，并以字符串形式返回"""
        if self.SCPI_NEW_FLAG:
            keyword = "SYST:BUZZ?"
        else:
            keyword = "BUZZ?"
        return self.query(keyword).rstrip()

    def get_cymometer_value_float(self):
        """获取硬件频率计的值，并以数据形式返回"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FREQ?"
        else:
            command = "CYMT_HW?"
        str_data = self.query(command)
        if "10Hz" in str_data:
            value = _MEAERROR
        else:
            try:
                value = self.value_strip_unit(str_data)
                if value<=10:
                    value = _MEAERROR
            except:
                value = _MEAERROR
        return value

    def get_auto_cal(self):  # 无法执行
        """执行一次自校正,并返回执行状态，成功返回0"""
        command = "*CAL?"
        return self.query(command)

    def set_screen_saver_state(self, state):
        """设置是否开启屏幕保护
        Args:
            enabled: {OFF,1MIN,5MIN,10MIN,30MIN,60MIN}
        """
        if self.SCPI_NEW_FLAG:
            command = "SYST:SSAV "+ state.upper()
        else:
            command = "SCSV " + state.upper()
        self.write(command)

    def get_screen_saver_state(self):
        """获取屏幕保护状态"""
        if self.SCPI_NEW_FLAG:
            command = "SYST:SSAV?"
        else:
            command = "SCSV?"
        return self.query(command).rstrip()

    def set_ip_address(self, ip_add0, ip_add1, ip_add2, ip_add3):#
        """更改IP地址
        Args:
            ip_add0: 0~255
        """
        if self.SCPI_NEW_FLAG:
            command = "SYST:COMM:LAN:IPAD '{}.{}.{}.{}'".format(ip_add0, ip_add1, ip_add2, ip_add3)
        else:
            command = "CONET " + str(ip_add0) + "," + str(ip_add1) + "," + str(ip_add2) + "," + str(ip_add3)
        self.write(command)

    def get_ip_address(self):
        """获取IP地址，并以字符串形式返回"""
        if self.SCPI_NEW_FLAG:
            command = "SYST:COMM:LAN:IPAD?"
            rtn =  self.query(command).rstrip()
            rtn = rtn.strip("\"")
        else:
            command = "CONET?"
            rtn = self.query(command).rstrip()
        return rtn

    def sys_month_string_adapter(self,month,flag):
        Param_new=["1","2","3","4","5","6","7","8","9","10","11","12"]
        Param_old=["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP","OCT", "NOV", "DEC"]
        if flag:
            index = Param_old.index(month)
            mode = Param_new[index]
        else:
            index = Param_new.index(month)
            mode = Param_old[index]
        return mode

    def set_date(self, day, month, year, hour, minute, second):
        """设置设备内部时钟,按照以下规则输入新指令
        Args:
            day: = 1 to 31
            month: = 1-12
            year: = 1990~2089
            hour: = 0~23
            minute: = 0~59
            second: = 0~59
        """
        if self.SCPI_NEW_FLAG:
            command = "SYST:DATE "+year+month+day
            self.write(command)
            command = "SYST:TIME " +hour+minute+second
            self.write(command)
        else:
            month = self.sys_month_string_adapter(month,False)
            command = ("DATE " + str(day) + "," + month.upper() + "," + str(year) + ","
                       + str(hour) + "," + str(minute) + "," + str(second))
        self.write(command)

    def get_date(self):
        """获取设备内部时钟时间，并以字符串形式返回"""
        if self.SCPI_NEW_FLAG:
            command = "SYST:DATE?"
            data = self.query(command).rstrip()
            command = "SYST:TIME?"
            clock = self.query(command).rstrip()
            print(type(data),type(clock))
        else:
            command = "DATE?"
            data = "None"
            clock = "None"
        return data+clock

    # ---------------------------------------------------------------------------
    #
    # Pass/Fail
    #
    # ---------------------------------------------------------------------------
    def set_passfail_state(self, state):
        """设置Mask Test开关"""
        if self.SCPI_NEW_FLAG:
            keyword = "MTES "
        else:
            keyword = "PFEN "
        command = keyword + state.upper()
        self.write(command)

    def get_passfail_state(self):
        """获取Mask Test状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES?"
        else:
            command = "PFEN?"
        return self.query(command).rstrip()

    def set_passfail_source(self, source):
        """设置信源"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:SOUR " + source.upper()
        else:
            command = "PFSC " + source.upper()
        self.write(command)

    def get_passfail_source(self):
        """获取信源"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:SOUR?"
        else:
            command = "PFSC?"
        return self.query(command).rstrip()

    def set_passfail_msg_display(self, state):
        """设置MAsk Test信息显示状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "MTES:IDIS "
        else:
            keyword = "PFDS "
        command =keyword + state.upper()
        self.write(command)

    def get_passfail_msg_display(self):
        """ 获取信息显示状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:IDIS?"
        else:
            command = "PFDS?"
        return self.query(command).rstrip()

    def set_passfail_operate(self, state):
        """设置操作状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "MTES:OPER "
        else:
            keyword = "PFOP "
        command = keyword + state.upper()
        self.write(command)

    def get_passfail_operate(self):
        """获取操作状态
        """
        if self.SCPI_NEW_FLAG:
            command = "MTES:OPER?"
        else:
            command = "PFOP?"
        return self.query(command).rstrip()

    def get_passfail_data(self):
        """获取PASS/FAIL 测试数据"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:COUN?"
        else:
            command = "PFDD?"
        return self.query(command).rstrip()

    def set_clear_passfail_data(self):
        """设置PASS/FAIl测试计数器数据为0"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:RESet"
        else:
            command = "PACL"
        self.write(command)

    def set_passfail_mask(self, xmask, ymask):
        """设置P/F规则中的X,Y参数
        Args:
            xmask: 0.04~4.0
            ymask: 0.04~4.0
        """
        if self.SCPI_NEW_FLAG:
            command = "MTES:MASK:CREate {},{}".format(xmask,ymask)
        else:
            command = "PFST XMASK,{},YMASK,{}".format(xmask,ymask)
        self.write(command)

    def set_create_passfail_mask(self, xmask=None, ymask=None):
        """设置P/F规则并创建"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:MASK:CREate {},{}".format(xmask, ymask)
        else:
            if xmask!=None or ymask!=None:
                command = "PFST XMASK,{},YMASK,{}".format(xmask, ymask)
                self.write(command)
            command = "PFCM"
        self.write(command)

    def get_passfail_mask(self):
        """获取P/F规则，并以字符串形式返回"""
        if not self.SCPI_NEW_FLAG:
            command = "PFST?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_passfail_buzzer(self, state):
        """设置失败声音输出"""
        if self.SCPI_NEW_FLAG:
            keyword = "MTES:FUNC:BUZZ "
        else:
            keyword = "PFBF "
        command = keyword + state.upper()
        self.write(command)

    def get_passfail_buzzer(self):
        """获取失败声音输出状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:BUZZ?"
        else:
            command = "PFBF?"
        return self.query(command).rstrip()

    def set_passfail_stop_fail(self, state):
        """设置失败即停状态 """
        if self.SCPI_NEW_FLAG:
            keyword = "MTES:FUNC:SOF "
        else:
            keyword = "PFFS "
        command = keyword + state.upper()
        self.write(command)

    def get_passfail_stop_fail(self):
        """获取失败即停状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:SOF?"
        else:
            command = "PFFS?"
        return self.query(command).rstrip()

    def set_passfail_failure_history(self, state):
        """设置存储失败帧状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:FTH " + state.upper()
            self.write(command)

    def get_passfail_failure_history(self):
        """获取存储失败帧状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:FTH?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_passfail_capture_fail(self, state, path):
        """设置失败截图状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:COF %s,%s" % (state, path)
            self.write(command)

    def get_passfail_capture_fail(self):
        """获取失败截图状态"""
        if self.SCPI_NEW_FLAG:
            command = "MTES:FUNC:COF?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_passfail_saveload(self, path_type, path):
        """设置P/F模板存储位置及存储调出动作
        Args：
            path_type: {INTernal,EXTernal},IN代表内部存储，EX代表外部存储
            path:1-8 or "string"
        """
        if self.SCPI_NEW_FLAG:
            if "INT" in path_type.upper():
                command = "MTES:MASK:LOAD {},{}".format(path_type,path)
            else:
                command = "MTES:MASK:LOAD {},\"{}\"".format(path_type,path)
            self.write(command)

    # -------------------------------------------------------------------------
    #
    # Digital
    #
    # -------------------------------------------------------------------------
    def set_digital_switch(self, mode):
        """设置数字通道的开关状态"""
        if self.SCPI_NEW_FLAG:
            keyword = "DIG "
        else:
            keyword = "DI:SW "
        command = keyword + mode.upper()
        self.write(command)

    def get_digital_switch(self):
        """"""
        if self.SCPI_NEW_FLAG:
            keyword = "DIG?"
        else:
            keyword = "DI:SW?"
        return self.query(keyword).rstrip()

    def digital_source(self, source, flag):
        Param_new = ["THR1","THR2"]
        Param_old = ["L8","H8"]
        if flag:
            index = Param_old.index(source)
            source = Param_new[index]
        else:
            index = Param_new.index(source)
            source = Param_old[index]
        return source

    def set_digital_threshold_mode(self, source, mode):
        """设置数字通道的阈值模式"""
        if self.SCPI_NEW_FLAG:
            source = self.digital_source(source,True)
            command = "DIG:%s %s" % (source, mode.upper())
        else:
            command = source.upper() + ":TSM " + mode.upper()
        self.write(command)

    def get_digital_threshold_mode(self,source):
        """"""
        if self.SCPI_NEW_FLAG:
            source = self.digital_source(source, True)
            command =  "DIG:%s?" % source
        else:
            command =  source.upper() + ":TSM?"
        return self.query(command).rstrip()

    def set_digital_threshold(self, source, value):
        """设置数字通道的阈值电平"""
        if self.SCPI_NEW_FLAG:
            source = self.digital_source(source, True)
            command = "DIG:%s CUST,%s" % (source, str(value))
        else:
            command = source.upper() +":CUS " + str(value)
        self.write(command)

    def get_digital_threshold(self, source):
        """获取数字通道的阈值电平"""
        if self.SCPI_NEW_FLAG:
            source = self.digital_source(source, True)
            command = "DIG:%s?" % source
            value = self.query(command).rstrip()
            thrd_value = value.split(",")
            return thrd_value[1]
        else:
            command =  source +":CUS?"
            return self.query(command).rstrip()

    def set_digital_height(self, height):
        """设置数字通道高度"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:HEIG " + str(height)
            self.write(command)

    def get_digital_height(self):
        """获取数字通道高度"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:HEIG?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_digital_position(self, position):
        """设置数字通道位置"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:POS " + str(position)
            self.write(command)

    def get_digital_position(self):
        """获取数字通道位置"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:POS?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_digital_deskew(self, skew):
        """设置数字通道时滞"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:SKEW " + str(skew)
            self.write(command)

    def get_digital_deskew(self):
        """获取数字通道时滞"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:SKEW?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_digital_trace_display(self, digital, state):
        """设置数字通道显示状态"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:%s %s" % (digital, state)
        else:
            command = "%s:TRACE %s" % (digital, state)
        self.write(command)

    def get_digital_trace_display(self, digital):
        """获取数字通道显示状态"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:%s?" % digital
        else:
            command = "%s:TRACE?" % digital
        return self.query(command).rstrip()

    def set_digital_bus_display(self, bus, state):
        """设置数字通道总线显示状态
        state:{ON|OFF}"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:BUS%s:DISP %s" % (bus, state)
            self.write(command)

    def get_digital_bus_display(self, bus):
        """获取数字通道总线显示状态"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:BUS%s:DISP?" % (bus)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_digital_data_format(self, bus, mode):
        """设置数字通道总线数字格式"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:%s:FORM %s" % (bus, mode)
            self.write(command)

    def get_digital_data_format(self, bus):
        """获取数字通道总线数字格式"""
        if self.SCPI_NEW_FLAG:
            command = "DIG:%s:FORM?" % (bus)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE
    # -----------------------------------------------------------------------------
    #
    # System
    #
    # -----------------------------------------------------------------------------
    def get_reg_alst(self):
        """获取和清除所有状态寄存器的内容,并以字符串形式返回"""
        command = "ALST?"
        return self.query(command).rstrip()

    def get_reg_cmr(self):
        """获取和清除指令错误寄存器的内容"""
        command = "CMR?"
        return self.query(command).rstrip()

    def get_reg_ddr(self):
        """获取和清除DDR上的内容"""
        command = "DDR?"
        return self.query(command).rstrip()

    def get_reg_exr(self):
        """获取和清除执行错误寄存器上的内容"""
        command = "EXR?"
        return self.query(command).rstrip()

    def get_reg_inr(self):  # 返回值一直为8193
        """获取和清除内部状态改变寄存器上的内容"""
        command = "INR?"
        return self.query(command).rstrip()

    def set_reg_clear_all(self):
        """清除所有状态寄存器"""
        command = "*CLS"
        self.write(command)

    def set_reg_ese(self, value):
        """设置事件状态使能寄存器
        Args:
            value: {0~255}
        """
        command = "*ESE " + str(value)
        self.write(command)

    def get_reg_ese(self):
        """查询事件状态使能寄存器"""
        command = "*ESE?"
        return self.query(command).rstrip()

    def get_reg_esr(self):
        """查询并清除事件状态寄存器内容"""
        command = "*ESR?"
        return self.query(command).rstrip()

    def set_reg_opc(self):
        """对标准事件状态寄存器OPC位进行写1操作"""
        command = "*OPC"
        self.write(command)

    def get_reg_opc(self):
        """查询上条命令是否执行完"""
        command = "*OPC?"
        return self.query(command).rstrip()

    def set_reg_sre(self, value):
        """设置服务请求使能寄存器
        Args:
            value: {0~255}
        """
        command = "*SRE " + str(value)
        self.write(command)

    def get_reg_sre(self):
        """查询服务请求使能寄存器"""
        command = "*SRE?"
        return self.query(command).rstrip()

    def get_reg_stb(self):
        """查询状态寄存器"""
        command = "*STB?"
        return self.query(command).rstrip()

    # ------------------------------KeyboardLock-------------------------------
    def set_key_oper_lock(self, state):
        """设置面板按键锁
        Args:
            state: {ON,OFF}
        """
        command = "LOCK " + state.upper()
        self.write(command)

    def get_key_oper_lock(self):
        """查询面板按键锁状态"""
        command = "LOCK?"
        self.write(command)
        return self.read().rstrip()

    def set_syfp(self, key, step=0):
        """设置虚拟按键
        key:按键名，详见keylist。含Knob则为旋钮，其余为按键
        step:{-1,0,1},虚拟键类型为旋钮时需要传入该参数，-1为逆时针-1，1为顺时针+1，0为按下"""
        keylist = ["Menu", "F1", "F2", "F3", "F4", "F5", "F6", "HoriDivKnob","","",
                   "HoriPosKnob", "AutoSet","RunStop","Default","AWG","MultiKnob","TrigLevelKnob","Auto","Setup","Normal",
                   "Single","","Cursors","Display","Utility","Print","Measure","Acquire","SaveRecall","Decode",
                   "Digital","Math","Ref","","","C1VdivKnob","C2VdivKnob","C3VdivKnob","C4VdivKnob","CH1",
                   "CH2","CH3","CH4","C1PosKnob","C2PosKnob","C3PosKnob","C4PosKnob","ClearSweeps","History","Roll",
                   "Search","Navigate","Left","Middle","Right","Touch","Zoom","Analysis","MultiVdivKnob","MultiPosKnob",
                   "MathVdivKnob","MathPosKnob","OfstUp","OfstDown","PosLeft","PosRight","Scope","Meter","Recorder","Hide",
                   "Shift","TrigLevel","VDiv","SDiv","NSDiv","MVDiv"]
        try:
            key_id = str(keylist.index(key))
            if self.SCPI_NEW_FLAG:#SHS(V1.1.18及以前)暂未支持此条新指令
                command = "SYSTem:KEYPress"
            else:
                command = "SY_FP"
            self.write("{} {},{}".format(command,key_id,step))
        except:
            print("Cannot find the key")

    # -------------------------------Other-----------------------------------------
    def create_cal_file(self):
        """"""
        command = "LOAD:CALI:FILE?"
        self.write(command)
        rcv = self.read_raw()
        data = rcv.rstrip()
        return data

    # ---------------------------serial trigger------------------------------------
    def serial_condition_string(self, protocol, type, flag):
        if protocol == "IIC":
            Param_new = ["STARt", "STOP", "RESTart", "NACK", "EEPRom", "7ADDRess", "10ADDRess", "DLENgth"]
            Param_old = ["START", "STOP", "RESTART", "NOACK", "EEPROM", "7ADDA", "10ADDA", "DALENTH"]
        if protocol == "UART":
            Param_new = ["STARt", "STOP", "DATA", "ERRor"]
            Param_old = ["START", "STOP", "DATA", "ERROR"]
        if protocol == "CAN":
            Param_new = ["STARt", "REMote", "ID", "ID_AND_DATA", "ERRor"]
            Param_old = ["START", "REMOTE", "ID", "ID_AND_DATA", "ERROR"]
        if flag:
            index = Param_old.index(type)
            type = Param_new[index]
        else:
            index = Param_new.index(type)
            type = Param_old[index]
        return type

    def serial_iic_limit_string(self, limit, flag):
        Param_new = ["EQUal","GREaterthan","LESSthan"]
        Param_old = ["EQUAL","MORE","LESS"]
        if flag:
            index = Param_old.index(limit)
            limit = Param_new[index]
        else:
            index = Param_new.index(limit)
            limit = Param_old[index]
        return limit

    def serial_iic_rw_string(self, rw, flag):
        Param_new = ["WRITe","READ","ANY"]
        Param_old = ["READ","WRITE","DONT_CARE"]
        if flag:
            index = Param_old.index(rw)
            rw = Param_new[index]
        else:
            index = Param_new.index(rw)
            rw = Param_old[index]
        return rw

    def serial_spi_edge_string(self,edge, flag):
        Param_new = ["RISing","FALLing"]
        Param_old = ["RISING","FALLING"]
        if flag:
            index = Param_old.index(edge)
            edge = Param_new[index]
        else:
            index = Param_new.index(edge)
            edge = Param_old[index]
        return edge

    def serial_uart_equal_string(self,limit, flag):
        Param_new = ["EQUal","GREaterthan","LESSthan"]
        Param_old = ["EQUAL","MORE","LESS"]
        if flag:
            index = Param_old.index(limit)
            limit = Param_new[index]
        else:
            index = Param_new.index(limit)
            limit = Param_old[index]
        return limit

    def serial_baud_string(self,protocol,baud,flag):
        if protocol == "UART":
            Param_new = ["600bps", "1200bps", "2400bps", "4800bps", "9600bps", "19200bps", "38400bps", "57600bps","115200bps"]
            Param_old = ["600", "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200"]
        if protocol == "CAN":
            Param_new = ["5kbps", "10kbps", "20kbps", "50kbps", "100kbps", "125kbps", "250kbps", "500kbps", "800kbps","1Mbps"]
            Param_old = ["5K", "10K", "20K", "50K", "100K", "125K", "250K", "500K", "800K", "1M"]
        if protocol == "LIN":
            Param_new = ["600bps", "1200bps", "2400bps", "4800bps", "9600bps", "19200bps"]
            Param_old = ["600", "1200", "2400", "4800", "9600", "19200"]
        if flag:
            index = Param_old.index(baud)
            baud = Param_new[index]
        else:
            index = Param_new.index(baud)
            baud = Param_old[index]
        return baud

    def serial_uart_parity_string(self,par, flag):
        Param_new = ["NONE","ODD","EVEN","MARK","SPACe"]
        Param_old = ["NONE","ODD","EVEN","MARK","SPACE"]
        if flag:
            index = Param_old.index(par)
            par = Param_new[index]
        else:
            index = Param_new.index(par)
            par = Param_old[index]
        return par

    def set_trig_serial_type(self,protocol):
        """设置总线协议
               protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:TYPE %s"% (protocol)
            self.write(command)

    def get_trig_serial_type(self):
        """获取总线协议
        protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:TYPE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_serial_source(self, protocol, src, type="SOUR"):
        """设置串行触发信源
        protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|}
        src_type:IIC={SCLS|SDAS},SPI={CLKS|MISOS|MOSIS|CSS|NCSS},UART={RXS|TXS},IIS={BCLKS|WSS|DS}
        source:{C1~C4,D0~D15}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:%s %s"% ( protocol, type, src)
            self.write(command)
        else:
            if protocol in ["IIC","SPI","UART"]:
                command = "TR%:% %"% (protocol,type[:-1], src)
                self.write(command)
            elif protocol == "LIN":
                command = "TRLIN:SRC {}".format(src)
                self.write(command)


    def get_trig_serial_source(self, protocol, type="SOUR"):
        """获取串行触发信源
        protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT}
        src_type:IIC={SCLS|SDAS},SPI={CLKS|MISOS|MOSIS|CSS|NCSS},UART={RXS|TXS},IIS={BCLKS|WSS|DS}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:{}:{}?".format(protocol, type)
            return self.query(command).rstrip()
        else:
            if protocol in ["IIC","SPI","UART"]:
                command = "TR{}:{}?".format(protocol,type[:-1])
                return self.query(command).rstrip()
            elif protocol == "LIN":
                command = "TRLIN:SRC?"
                return self.query(command).rstrip()
            else:
                return _SCPI_NONE

    def set_trig_serial_threshold(self,protocol,value,type="THR"):
        """设置串行触发阈值
            protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT}
            t_type: IIC={SCLT|SDAT},SPI={CLKT|MISOT|MOSIT|CST|NCST},UART={RXT|TXT},IIS={BCLKT|WSTH|DTHR},M1553={UTHR|LTHR}
            value:单位V"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:{}:{} {}".format(protocol,type,value)
            self.write(command)

    def get_trig_serial_threshold(self,protocol,type="THR"):
        """获取串行触发阈值
         protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT}
        type:t_type: IIC={SCLT|SDAT},SPI={CLKT|MISOT|MOSIT|CST|NCSST},UART={RXT|TXT},IIS={BCLKT|WSTH|DTHR}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:{}:{}?".format(protocol,type)
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_serial_baud(self, protocol, baud,type="BAUD"):
        """设置串行触发波特率
        protocol:{UART|CAN|LIN|FLEXray|CANFd}
        uart baud:{600bps|1200bps|2400bps|4800bps|9600bps|19200bps|38400bps|57600bps|115200bps|CUSTom[,<value>]} value:300~20000000
        can baud:{5kbps|10kbps|20kbps|50kbps|100kbps|125kbps|250kbps|500kbps|800kbps|1Mbps|CUSTom[,<value>]} value:5000~1000000
        lin baud:{600bps|1200bps|2400bps|4800bps|9600bps|19200bps|CUSTom[,<value>]} value:300~20000000
        flx baud:{2500kbps|5Mbps|10Mbps|CUSTom[,<value>]}value:1000000~20000000
        canfd nombaud:{10kbps"|25kbps|50kbps|100kbps|250kbps|1Mbps|CUSTom[,<value>]}value:10000~1000000
        canfd databaud:{500kbps|1Mbps|2Mbps|5Mbps|8Mbps|10Mbps|CUSTom[,<value>]value:100000~10000000"""

        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:%s %s" % ( protocol,type, baud)
        else:
            if protocol in ["UART", "CAN", "LIN"]:
                baud = self.serial_baud_string(baud, False)
                command = "TR%s:BAUD %s" % (protocol,baud)
        self.write(command)

    def get_trig_serial_baud(self, protocol,type="BAUD"):
        """获取串行触发波特率
        protocol:{UART|CAN|LIN|FLEXray|CANFd}
        CANFd:type={BAUDN,BAUDD}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:%s?" % ( protocol,type)
            baud = self.query(command).rstrip()
        else:
            if protocol in ["UART","CAN","LIN"]:
                command = "TR%s:BAUD?" % (protocol)
                baud = self.query(command).rstrip()
                baud = self.serial_baud_string(baud, True)
            else:
                baud = _SCPI_NONE
        return baud

    def set_trig_serial_bitorder(self, protocol, order):
        """设置比特流格式
        protocol:{SPI|UART|IIS}
        order:{LSB,MSB}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:BIT %s" % ( protocol, order)
        else:
            command = "TR%s BIT %s" % (protocol, order)
        self.write(command)

    def get_trig_serial_bitorder(self, protocol):
        """获取比特流格式
        protocol:{SPI|UART|IIS}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:BIT?" % (protocol)
        else:
            command = "TR%s:BIT?" %(protocol)
        return self.query(command).rstrip()

    def set_trig_serial_condition(self,protocol,type):
        """设置串行触发触发条件
        protocol:{IIC|UART|CAN|LIN|FLEXray|CANFd|IIS}
        IIC: type:{STARt|STOP|RESTart|NACK|EEPRom|7ADDRess|10ADDRess|DLENgth}
        UART: type:{STARt|STOP|DATA|ERRor}
        CAN、CANFd: type:{STARt|REMote|ID|ID_AND_DATA|ERRor}
        LIN: type:{BReak|ID|ID_AND_DATA|DATA_ERROR}
        FLEXray: type:{TSS|FRAMe|SYMBol|ERRor}
        IIS type:{DATA|MUTE|CLIP|GLITch|RISing|FALLing}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:COND %s" % (protocol,type)
        else:
            if protocol in ["IIC","UART","CAN"]:
                type = self.serial_condition_string(protocol, type, False)
                command = "TR%s:CON %s" % (protocol, type)
            elif protocol == "LIN":
                command = "TRLIN:CON %s"
        self.write(command)

    def get_trig_serial_condition(self,protocol):
        """获取串行触发触发条件
        protocol:{IIC|UART|CAN|LIN|FLEXray|CANFd|IIS}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:%s:COND?" % (protocol)
            rtn = self.query(command).rstrip()
        else:
            if protocol in ["IIC","UART","CAN"]:
                command = "TR%s:CON?" % (protocol)
                rtn = self.query(command).rstrip()
                rtn = self.serial_condition_string(rtn, True)
            elif protocol == "LIN":
                command = "TRLIN:CON?"
                rtn = self.query(command).rstrip()
            else:
                rtn = _SCPI_NONE
        return rtn

    def set_trig_iic_addr(self,addr):
        """设置IIC触发地址
        :param addr:0~127
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:ADDR %s" % (str(addr))
        else:
            command = "TRIIC:ADDR %s" % (str(addr))
        self.write(command)

    def get_trig_iic_addr(self):
        """获取IIC触发地址"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:ADDR?"
        else:
            command = "TRIIC:ADDR?"
        addr =  self.query(command).rstrip()
        return float(addr)

    def set_trig_iic_data1(self,data):
        """设置IIC触发数据1
        data:0~256"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DATA %s" % (str(data))
        else:
            command  = "TRIIC:DATA %s" % (str(data))
        self.write(command)

    def get_trig_iic_data1(self):
        """获取IIC触发数据1"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DATA?"
        else:
            command  = "TRIIC:DATA?"
        value = self.query(command).rstrip()
        return float(value)

    def set_trig_iic_data2(self,data):
        """设置IIC触发数据2
        data:0~256"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DAT2 %s" % (str(data))
        else:
            command  = "TRIIC:DAT2 %s" % (str(data))
        self.write(command)

    def get_trig_iic_data2(self):
        """获取IIC触发数据2"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DAT2?"
        else:
            command = "TRIIC:DAT2?"
        value = self.query(command).rstrip()
        return float(value)

    def set_trig_iic_qual(self,qual):
        """
        设置IIC触发限制条件
        :param range:{EQUal|GREaterthan|LESSthan}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:LIM %s" % (qual)
        else:
            qual = self.serial_iic_limit_string(qual,False)
            command ="TRIIC:QUAL %s" % (qual)
        self.write(command)

    def get_trig_iic_qual(self):
        """获取IIC触发限制条件"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:LIM?"
            qual =self.query(command).rstrip()
        else:
            command = "TRIIC:QUAL?"
            qual = self.query(command).rstrip()
            qual = self.serial_iic_limit_string(qual, True)
        return qual

    def set_trig_iic_rw(self,rw):
        """
        设置IIC触发读写位
        :param rw:{WRITe|READ|ANY}
        :return:
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:RWB %s" % (rw)
        else:
            rw=self.serial_iic_rw_string(rw,False)
            command = "TRIIC:RW %s" % (rw)
        self.write(command)

    def get_trig_iic_rw(self):
        """获取IIC触发读写位"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:RWB?"
            rtn =self.query(command).rstrip()
        else:
            command = "TRIIC:RW?"
            rtn =self.query(command).rstrip()
            rtn = self.serial_iic_rw_string(rtn,True)
        return rtn

    def set_trig_iic_dlen(self,dlength):
        """
        设置iic触发数据长度
        :param dlength:1~12
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DLEN %s" % (str(dlength))
        else:
            command="TRIIC:DLEN %s"% (str(dlength))
        self.write(command)

    def get_trig_iic_dlen(self):
        """获取IIC触发数据长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:DLEN?"
        else:
            command = "TRIIC:DLEN?"
        value = self.query(command).rstrip()
        return float(value)

    def set_trig_iic_alen(self,alength):
        """设置IIC触发地址长度
        alength: {7BIT,10BIT}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:ALEN %s" % (alength)
        else:
            command="TRIIC:ALEN %s"% (alength)
        self.write(command)

    def get_trig_iic_alen(self):
        """获取IIC触发地址长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIC:ALEN?"
        else:
            command = "TRIIC:ALEN?"
        return self.query(command).rstrip()

    def set_trig_spi_edge(self,type):
        """设置SPI边沿类型
        type:{RISing,FALLing}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:LATC %s" % (type)
        else:
            type = self.serial_spi_edge_string(type,False)
            command = "TRSPI:CLK:EDGE %s" % (type)
        self.write(command)

    def get_trig_spi_edge(self):
        """获取SPI边沿类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:LATC?"
            type =  self.query(command).rstrip()
        else:
            command = "TRSPI:CLK:EDGE?"
            type = self.query(command).rstrip()
            type = self.serial_spi_edge_string(type, TabError)
        return type

    def set_trig_spi_cstp(self,type):
        """设置SPI 片选类型
        type:{NCS|CS|TIMEOUT}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:CSTY %s" % (type)
        else:
            command = "TRSPI:CSTP %s" % (type)
        self.write(command)

    def get_trig_spi_cstp(self):
        """获取SPI 片选类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:CSTY?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")[0]
        else:
            command = "TRSPI:CSTP?"
            rtn = self.query(command).rstrip()
        return rtn.upper()

    def set_trig_spi_time(self,times):
        """设置SPI超时时间
        times:1.00E-07~5.00E-03"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:CSTY TIMeout,%s" % (str(times))
            self.write(command)
        else:
            command = "TRSPI:CLK:TIM %s" % (str(times))
            self.write(command)

    def get_trig_spi_time(self):
        """获取SPI超时时间"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:CSTY?"
            rtn = self.query(command).rstrip()
            rtn = rtn.split(",")[1]
        else:
            command = "TRSPI:CLK:TIM?"
            rtn = self.query(command).rstrip()
        return float(rtn)

    def set_trig_spi_trty(self,type):
        """设置SPI触发类型
        type:{MOSI,MISO}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:TTYP %s" % (type)
        else:
            command = "TRSPI:TRTY %s"% type
        self.write(command)

    def get_trig_spi_trty(self):
        """获取SPI触发类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:TTYP?"
        else:
            command = "TRSPI:TRTY?"
            rtn = self.query(command).rstrip()
        return self.query(command).rstrip()

    def set_trig_spi_dlen(self,dlen):
        """设置SPI数据长度
        dlen:4~96"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:DLEN %s" % (str(dlen))
        else:
            command = "TRSPI:DLEN %s" % (str(dlen))
        self.write(command)

    def get_trig_spi_dlen(self):
        """获取SPI数据长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:DLEN?"
        else:
            command = "TRSPI:DLEN?"
        return float(self.query(command).rstrip())

    def set_trig_spi_dvalue(self,value):
        """设置SPI所有位
        value：{"0","1","X"}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:SPI:DATA %s" % (str(value))
        else:
            command = "TRSPI:DATA %s"% (str(value))
        self.write(command)

    def get_trig_spi_dvalue(self):
        """获取SPI所有位"""
        return _SCPI_NONE
        #if self.SCPI_NEW_FLAG:
        #command = "TRIG:SPI:DATA?"
        #else:
        #command="TRSPI:DATA?"
        #return self.query(command).rstrip()

    def set_trig_uart_trty(self,type):
        """设置UART触发类型
        tyoe:RX,TX"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:TTYP %s" % (type)
        else:
            command = "TRUART:TRTY %s"% type
        self.write(command)

    def get_trig_uart_trty(self):
        """获取UART触发类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:TTYP?"
        else:
            command = "TRUART:TRTY?"
        return self.query(command).rstrip()

    def set_trig_uart_limit(self,limit):
        """设置UART的比较条件
        limit:{EQUal|GREaterthan|LESSthan}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:LIM %s" % (limit)
        else:
            limit = self.serial_uart_equal_string(limit,False)
            command = "TRUART:QUAL %s" % (limit)
        self.write(command)

    def get_trig_uart_limit(self):
        """获取UART比较条件"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:LIM?"
            limit = self.query(command).rstrip()
        else:
            command="TRUART:QUAL?"
            limit = self.query(command).rstrip()
            limit = self.serial_uart_equal_string(limit, True)
        return limit

    def set_trig_uart_data(self,data):
        """设置UART触发数据
        data:0~255"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:DATA %s" % (str(data))
        else:
            command="TRUART:DATA %s"% str(data)
        self.write(command)

    def get_trig_uart_data(self):
        """获取UART触发数据"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:DATA?"
        else:
            command = "TRUART:DATA?"
        return float(self.query(command).rstrip())

    def set_trig_uart_dlen(self, dlen):
        """设置UART的数据长度
        dlen:5~8"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:DLEN %s" % (str(dlen))
        else:
            command = "TRUART:DLEN %s"% str(dlen)
        self.write(command)

    def get_trig_uart_dlen(self):
        """获取UART的数据长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:DLEN?"
        else:
            command = "TRUART:DLEN?"
        return float(self.query(command).rstrip())

    def set_trig_uart_par(self, par):
        """设置UART的奇偶校验
        par:{NONE|ODD|EVEN|MARK|SPACe}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:PAR %s" % (par)
        else:
            par=self.serial_uart_parity_string(par,False)
            command = "TRUART:PAR %s"%(par)
        self.write(command)

    def get_trig_uart_par(self):
        """获取UART的奇偶校验"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:PAR?"
            par = self.query(command).rstrip()
        else:
            command = "TRUART:PAR?"
            par = self.query(command).rstrip()
            par=self.serial_uart_parity_string(par,True)
        return par

    def set_trig_uart_pol(self, pol):
        """设置UART的空闲电平
        pol:{LOW|HIGH}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:IDLE %s" % (pol)
        else:
            command = "TRUART:POL %s" % pol
        self.write(command)

    def get_trig_uart_pol(self):
        """获取UART的空闲电平"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:IDLE?"
        else:
            command = "TRUART:POL?"
        return self.query(command).rstrip()

    def set_trig_uart_stop(self, stop):
        """设置UART停止位
        stop:{1,1.5,2}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:STOP %s" % str(stop)
        else:
            command = "TRUART:STOP %s" % str(stop)
        self.write(command)

    def get_trig_uart_stop(self):
        """获取UART的停止位"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:UART:STOP?"
        else:
            command = "TRUART:STOP?"
        return float(self.query(command).rstrip())

    def set_trig_can_idl(self, value):
        """设置CAN id长度
        <value>:= {11BITS,29BITS}
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:IDL %s" % (value)
        else:
            command = "TRCAN:IDL %s"% value
        self.write(command)

    def get_trig_can_idl(self):
        """获取CAN id长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:IDL?"
        else:
            command = "TRCAN:IDL?"
        return self.query(command).rstrip()

    def set_trig_can_id(self,id):
        """设置CAN id
        id:0~536870911"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:ID %s" % str(id)
        else:
            command = "TRCAN:ID %s"% str(id)
        self.write(command)

    def get_trig_can_id(self):
        """获取CAN id"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:ID?"
        else:
            command = "TRCAN:ID?"
        return float(self.query(command).rstrip())

    def set_trig_can_data(self,data):
        """设置CAN数据1
        data:0~256
        """
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:DATA %s" % str(data)
        else:
            command ="TRCAN:DATA %s" % str(data)
        self.write(command)

    def get_trig_can_data(self):
        """获取CAN数据1"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:DATA?"
        else:
            command = "TRCAN:DATA?"
        return float(self.query(command).rstrip())

    def set_trig_can_dat2(self,data):
        """设置CAN数据2
        data:0~256"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:DAT2 %s" % str(data)
        else:
            command = "TRCAN:DAT2 %s"% str(data)
        self.write(command)

    def get_trig_can_dat2(self):
        """获取CAN数据2"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CAN:DAT2?"
        else:
            command = "TRCAN:DAT2?"
        return float(self.query(command).rstrip())

    def set_trig_lin_id(self,id):
        """设置LIN ID
        id:0~64"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ID %s" % str(id)
        else:
            command = "TRLIN:ID %s"% str(id)
        self.write(command)

    def get_trig_lin_id(self):
        """获取LIN ID"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ID?"
        else:
            command = "TRLIN:ID?"
        return float(self.query(command).rstrip())

    def set_trig_lin_data(self,data):
        """设置LIN 数据1
        data:0~256"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:DATA %s" % str(data)
        else:
            command = "TRLIN:DATA %s"% str(data)
        self.write(command)

    def get_trig_lin_data(self):
        """获取LIN数据1"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:DATA?"
        else:
            command = "TRLIN:DATA?"
        return float(self.query(command).rstrip())

    def set_trig_lin_dat2(self, data):
        """设置LIN数据2
        data:0~256"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:DAT2 %s" % str(data)
        else:
            command = "TRLIN:DAT2 %s"% str(data)
        self.write(command)

    def get_trig_lin_dat2(self):
        """获取LIN数据2"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:DAT2?"
        else:
            command = "TRLIN:DAT2?"
        return float(self.query(command).rstrip())

    #-------------仅self.SCPI_NEW_FLAG为True时有效------------
    def set_trig_lin_par(self,par):
        """设置LIN报头奇偶校验状态
        par:{0,1}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:PAR %s" % str(par)
            self.write(command)

    def get_trig_lin_par(self):
        """获取LIN报头奇偶校验状态"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:PAR?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_lin_sync(self,sync):
        """设置LIN同步字节检测状态
        sync:{0,1}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:SYNC %s" % str(sync)
            self.write(command)

    def get_trig_lin_sync(self):
        """获取LIN同步字节检测状态"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:SYNC?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_lin_check(self,check):
        """设置LIN校验和检测状态"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:CHEC %s" % str(check)
            self.write(command)

    def get_trig_lin_check(self):
        """获取LIN校验和检测状态"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:CHEC?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_lin_err_id(self,id):
        """设置LIN错误帧号ID
        id:0~63"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:ID %s" % (id)
            self.write(command)

    def get_trig_lin_err_id(self):
        """获取 LIN 错误帧号ID"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:ID?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_lin_version(self,stan):
        """设置LIN协议版本
        stan:{0,1}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:STAN %s" % (stan)
            self.write(command)

    def get_trig_lin_version(self):
        """获取LIN协议版本"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:STAN?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_lin_dlen(self,dlen):
        """设置LIN数字长度
        dlen:1~8"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:DLEN %s" % (dlen)
            self.write(command)

    def get_trig_lin_dlen(self):
        """获取 LIN 数字长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:LIN:ERR:DLEN?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_flexray_frameid(self,id):
        """设置flexray ID
        id:0~2047"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:ID %s" % str(id)
            self.write(command)

    def get_trig_flexray_frameid(self):
        """获取flexray ID"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:ID?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_flexray_compare(self,comp):
        """设置flexray 比较类型
        comp:{ANY|EQUal|GREaterthan|LESSthan}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:COMP %s" % (comp)
            self.write(command)

    def get_trig_flexray_compare(self):
        """获取flexray 比较类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:COMP?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_flexray_cycle(self,cycle):
        """设置flexray 周期数量
        cycle:0~63"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:CYCL %s" % str(cycle)
            self.write(command)

    def get_trig_flexray_cycle(self):
        """获取flexray 周期数量"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:CYCL?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_flexray_repetition(self,repe):
        """设置flexray 重复系数
        repe:{1|2|4|8|16|32|64}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:REP %s" % str(repe)
            self.write(command)

    def get_trig_flexray_repetition(self):
        """获取flexray 重复系数"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:FLEX:FRAM:REP?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_canfd_frametype(self, frame):
        """设置canfd帧类型
        frame:{BOTH|CAN|CANFd}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:FTYP %s" % (frame)
            self.write(command)

    def get_trig_canfd_frametype(self):
        """获取canfd 帧类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:FTYP?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_canfd_id(self, id):
        """设置canfd ID
        id:0~2047"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:ID %s" % str(id)
            self.write(command)

    def get_trig_canfd_id(self):
        """获取canfd ID"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:ID?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_canfd_data(self, data):
        """设置CAN FD数据1
        data:0~255"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:DAT2 %s" % str(data)
            self.write(command)

    def get_trig_canfd_data(self):
        """获取CANFD数据1"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:DAT2?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_canfd_dat2(self, data):
        """设置CAN FD数据2
        data:0~255"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:DAT2 %s" % str(data)
            self.write(command)

    def get_trig_canfd_dat2(self):
        """获取CANFD数据2"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:DAT2?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_canfd_idlength(self, idlength):
        """设置canfd ID长度
        idlength:{11BITS|29BITS}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:IDL %s" % (idlength)
            self.write(command)

    def get_trig_canfd_idlength(self):
        """获取canfd ID长度"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:CANF:IDL?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_iis_edgetype(self,type):
        """设置I2S边沿类型
        type:{RISing|FALLing}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:LATC %s" % (type)
            self.write(command)

    def get_trig_iis_edgetype(self):
        """获取I2S边沿类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:LATC?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_i2s_lch(self,lch):
        """设置I2S左声道类型
        lch:{LOW|HIGH}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:LCH %s" % (lch)
            self.write(command)

    def get_trig_i2s_lch(self):
        """获取I2S左声道类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:LCH?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_i2s_audio(self,audio):
        """设置I2S音频格式
        audio:{I2S|LJ|RJ}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:AVAR %s" % (audio)
            self.write(command)

    def get_trig_i2s_audio(self):
        """获取I2S音频格式"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:AVAR?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_i2s_channel(self,channel):
        """设置IIS通道
        channel:{LEFT|RIGHT}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:CHAN %s" % (channel)
            self.write(command)

    def get_trig_i2s_channel(self):
        """获取IIS的通道"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:CHAN?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_i2s_comptype(self,comp):
        """设置IIS比较类型
        comp:{EQUal|GREaterthan|LESSthan}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:COMP %s" % (comp)
            self.write(command)

    def get_trig_i2s_comptype(self):
        """获取IIS的比较类型"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:COMP?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_trig_i2s_value(self,value):
        """设置IIS的数据值
        value:0~7"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:VAL %s" % str(value)
            self.write(command)

    def get_trig_i2s_value(self):
        """获取IIS的数据值"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:VAL?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_trig_i2s_bits(self,bit,param="DLEN"):
        """设置IIS的通道位数、起始位、数据位数
        param={DLEN|CLEN|STAR}
        dlen:1~8"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:{} {}".format(param,bit)
            self.write(command)

    def get_trig_i2s_bits(self,param="DLEN"):
        """获取IIS的通道位数、起始位、数据位数
        param={DLEN|CLEN|STAR}"""
        if self.SCPI_NEW_FLAG:
            command = "TRIG:IIS:{}?".format(param)
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR


    #------------------------Decode--------------------------------------------
    def decode_copy_string(self,format,flag):
        Param_new = ["FROMtrigger","TOTRigger"]
        Param_old = ["TR_TO_DC","DC_TO_TR"]
        if flag:
            index = Param_old.index(format)
            format = Param_new[index]
        else:
            index = Param_new.index(format)
            format = Param_old[index]
        return format

    def decode_list_format_string(self,format,flag):
        Param_new = ["BINary","DECimal","HEX","ASCii"]
        Param_old = ["BIN","DEC","HEX","DEC"]
        if flag:
            index = Param_old.index(format)
            format = Param_new[index]
        else:
            index = Param_new.index(format)
            format = Param_old[index]
        return format

    def decode_edge_string(self,format,flag):
        Param_new = ["RISing","FALLing"]
        Param_old = ["RISING","FALLING"]
        if flag:
            index = Param_old.index(format)
            format = Param_new[index]
        else:
            index = Param_new.index(format)
            format = Param_old[index]
        return format

    def decode_uart_parity_string(self,par,flag):
        Param_new = ["NONE","ODD","EVEN","MARK","SPACe"]
        Param_old = ["NONE","EVEN","ODD","NONE","NONE"]
        if flag:
            index = Param_old.index(par)
            par = Param_new[index]
        else:
            index = Param_new.index(par)
            par = Param_old[index]
        return par

    def set_decode_list(self, state):
        """设置Decode列表状态
        state:{OFF|D1|D2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST %s" % (state)
        else:
            command = "DCPA LIST,%s" % (state)
        self.write(command)

    def get_decode_list(self):
        """获取Decode列表状态"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_line(self,line):
        """设置Decode列表行数
        line:1~7"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST:LINE %s" % (str(line))
        else:
            command = "DCPA LSNM,%s" % (str(line))
        self.write(command)

    def get_decode_line(self):
        """获取Decode列表行数"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST:LINE?"
            return float(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def set_decode_scroll(self,scroll):
        """设置Decode选中行数
        scroll:1~line"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST:SCR %s" % str(scroll)
        else:
            command = "DCPA LSSC,%s" % str(scroll)
        self.write(command)

    def get_decode_scroll(self):
        """获取Decode选中行数"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:LIST:SCR?"
            return self.query(command).rstrip()
        else:
            return _MEAERROR

    def set_decode_format(self, n, format):
        """设置Decode文本格式
        n:{1,2}
        format:{BINary|DECimal|HEX|ASCii}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:FORM %s" % (str(n),format)
        else:
            format = self.decode_list_format_string(format,False)
            command = "DCPA BUS,B%s,FOMT,%s"%(str(n),format)
        self.write(command)

    def get_decode_format(self,n):
        """获取Decode文本格式"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:FORM?"% (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_copy(self,operation):
        """设置解码和触发间的相互复制
        :param operation: {FROMtrigger|TOTRigger}
        """
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS1:COPY %s" % operation
        else:
            operation = self.decode_list_format_string(operation, False)
            command = "DCPA LINK,%s" % operation
        self.write(command)

    def set_deocde_bus_protocol(self,n,prot):
        """设置Decode总线协议
        prot:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|MANChester}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:PROT %s" % (str(n),prot)
            self.write(command)

    def get_deocde_bus_protocol(self,n):
        """获取Decode总线协议"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:PROT?"%(str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_source(self,n, protocol,src,type="SOUR"):
        """设置iic SCL源
        n:{1,2}
        protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|MANChester}
        src_type:IIC={SCLS|SDAS},SPI={CLKS|MISOS|MOSIS|CSS|NCSS},UART={RXS|TXS},IIS={BCLKS|WSS|DS}
        source:{C1~C4,D0~D15}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:{}:{} {}".format(n,protocol,type,src)
        else:
            if protocol == "IIC":
                command = "B{}:DCIC {},{}".format(n,type[:-1],src)
            elif protocol == "SPI":
                command = "B{}:DCSP {},{}".format(n,type[:-1],src)
            elif protocol == "UART":
                command = "B{}:DCUT {},{}".format(n,type[:-1],src)
            elif protocol == "LIN":
                command = "B{}:DCLN SRC,{}".format(n,src)
        self.write(command)

    def get_decode_source(self,n,protocol,type="SOUR"):
        """获取iic SCL源
        n:{1,2}
        protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|MANChester}
        src_type:IIC={SCLS|SDAS},SPI={CLKS|MISOS|MOSIS|CSS|NCSS},UART={RXS|TXS},IIS={BCLKS|WSS|DS}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:{}:{}?".format(n,protocol,type)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_threshold(self,n,protocol,value,type="THR"):
        """设置解码总线阈值
            n:{1,2}
            protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|MANChester}
            t_type: IIC={SCLT|SDAT},SPI={CLKT|MISOT|MOSIT|CST|NCSST},UART={RXT|TXT},IIS={BCLKT|WSTH|DTHR},M1553={UTHR|LTHR}
            value:单位V"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:{}:{} {}".format(n,protocol,type,value)
        else:
            if protocol == "IIC":
                command = "B{}:DCIC {},{}".format(n,type,value)
            elif protocol == "SPI":
                command = "B{}:DCSP {},{}".format(n,type,value)
            elif protocol == "UART":
                command = "B{}:DCUT {},{}".format(n,type,value)
            elif protocol == "LIN":
                command = "B{}:DCLN SRCT,{}".format(n,value)
        self.write(command)

    def get_decode_threshold(self,n,protocol,type="THR"):
        """获取解码总线阈值
        n:{1,2}
         protocol:{IIC|SPI|UART|CAN|LIN|FLEXray|CANFd|IIS|M1553|SENT|MANChester}
        type:t_type: IIC={SCLT|SDAT},SPI={CLKT|MISOT|MOSIT|CST|NCSST},UART={RXT|TXT},IIS={BCLKT|WSTH|DTHR}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:{}:{}?".format(n,protocol,type)
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_decode_bitorder(self, n, protocol, order):
        """设置比特流格式
        n:{1,2}
        protocol:{SPI|UART|IIS|MANChester}
        order:{LSB,MSB}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:%s:BIT %s" % (str(n), protocol, order)
        else:
            if protocol == "SPI":
                command = "B%s:DCSP BIT,%s" % (str(n), order)
            elif protocol == "UART":
                command = "B%s:DCUT BIT,%s" % (str(n), order)
        self.write(command)

    def get_decode_bitorder(self, n, protocol):
        """获取比特流格式
        n:{1,2}
        protocol:{SPI|UART|IIS|MANChester}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:%s:BIT?" % (str(n), protocol)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_baud(self, n, protocol, baud,type="BAUD"):
        """设置解码总线波特率
        n:{1,2}
        protocol:{UART|CAN|LIN|FLEXray|MANChester}
        uart baud:{600bps|1200bps|2400bps|4800bps|9600bps|19200bps|38400bps|57600bps|115200bps|CUSTom[,<value>]} value:300~20000000
        can baud:{5kbps|10kbps|20kbps|50kbps|100kbps|125kbps|250kbps|500kbps|800kbps|1Mbps|CUSTom[,<value>]} value:5000~1000000
        lin baud:{600bps|1200bps|2400bps|4800bps|9600bps|19200bps|CUSTom[,<value>]} value:300~20000000
        flx baud:{2500kbps|5Mbps|10Mbps|CUSTom[,<value>]}value:1000000~20000000
        canfd nombaud:{10kbps"|25kbps|50kbps|100kbps|250kbps|1Mbps|CUSTom[,<value>]}value:10000~1000000
        canfd databaud:{500kbps|1Mbps|2Mbps|5Mbps|8Mbps|10Mbps|CUSTom[,<value>]value:100000~10000000
        manch value:500~5000000
        type:{BAUDN|BAUDD}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:%s:%s %s" % (str(n), protocol,type, baud)
        else:
            if protocol == "UART":
                command = "B%s:DCUT BAUD,%s" % (str(n), baud)
            elif protocol == "CAN":
                command = "B%s:DCCN BAUD,%s" % (str(n), baud)
            elif protocol == "LIN":
                command = "B%s:DCLN BAUD,%s" % (str(n), baud)
        self.write(command)

    def get_decode_baud(self, n, protocol,type="BAUD"):
        """获取解码总线波特率
        n:{1,2}
        protocol:{UART|CAN|LIN|FLEXray|MANChester}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:%s:%s?" % (str(n), protocol,type)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_iic_rwbit(self,n,rw):
        """设置iic 读写位
        n:{1,2}
        rw:{OFF,ON}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIC:RWB %s" % (n,rw)
        else:
            command = "B%s:DCIC RW,%s" % (n,rw)
        self.write(command)

    def get_decode_iic_rwbit(self,n):
        """获取iic 读写位"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIC:RWB?"%(str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_spi_latchege(self,n,type):
        """设置SPI CLK边沿类型
        type:{RISing|FALLing}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:LATC %s" % (str(n),type)
        else:
            type = self.decode_edge_string(type,False)
            command = "B%s:DCSP EDGE,%s" % (str(n),type)
        self.write(command)

    def get_decode_spi_latchege(self,n):
        """获取SPI CLK边沿类型"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:LATC?"%(str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_spi_cstype(self,n,type):
        """设置SPI 片选类型
        type:{CS,NCS,TIMeout,[value]}
        value:1.00E-07~5.00E-03"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:CSTY %s"%(str(n),type)
        else:
            command = "B%s:DCSP CSTP,CS,%s"%(str(n),type)
        self.write(command)

    def get_decode_spi_cstype(self,n):
        """获取SPI 片选类型"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:CSTY?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_spi_dlenght(self,n,length):
        """设置SPI数据长度
        n:{1,2}
        length:4~32"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:DLEN %s" % (str(n),str(length))
        else:
            command = "B%s:DCSP DLEN,%s" % (str(n),str(length))
        self.write(command)

    def get_decode_spi_dlenght(self,n):
        """获取SPI数据长度"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SPI:DLEN?"%(str(n))
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_decode_uart_dlength(self, n, length):
        """设置UART数据长度
        n:{1,2}
        length:5~8"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:DLEN %s" % (str(n), str(length))
        else:
            command = "B%s:DCUT DLEN,%s"% (str(n), str(length))
        self.write(command)

    def get_decode_uart_dlength(self, n):
        """获取UART数据长度"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:DLEN?" % (str(n))
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_decode_uart_parity(self, n, parity):
        """设置UART奇偶校验
        n:{1,2}
        parity:{NONE|ODD|EVEN|MARK|SPACe}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:PAR %s" % (str(n), parity)
        else:
            parity = self.decode_uart_parity_string(parity,False)
            command = "B%s:DCUT PAR,%s" % (str(n), parity)
        self.write(command)

    def get_decode_uart_parity(self, n):
        """获取UART奇偶校验
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:PAR?" % (str(n))
            return self.query(command).rstrip()

    def set_decode_uart_stop(self, n, bit):
        """设置UART停止位
        n:{1,2}
        bit:{1,1.5,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:STOP %s" % (str(n), str(bit))
        else:
            command = "B%s:DCUT BIT,%s" % (str(n), str(bit))
        self.write(command)

    def get_decode_uart_stop(self, n):
        """获取UART停止位"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:STOP?" % (str(n))
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_decode_uart_idle(self, n, idle):
        """设置UART空闲电平
        n:{1,2}
        idel:{LOW,HIGH}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:IDLE %s" % (str(n), idle)
        else:
            command = "B%s:DCUT POL,%s" % (str(n), idle)
        self.write(command)

    def get_decode_uart_idle(self, n):
        """获取UART空闲电平
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:UART:IDLE?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_canfd_baudnormal(self,n,baud):
        """设置CANFD标准波特率
        n:{1,2}
        baud:{10kbps|25kbps|50kbps|100kbps|250kbps|1Mbps|CUSTom[,<value>]}
        value:10000~1000000"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:CANF:BAUDN %s" % (str(n), baud)
            self.write(command)

    def get_decode_canfd_baudnormal(self, n):
        """获取CANFD标准波特率"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:CANF:BAUDN?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_canfd_bauddata(self,n,baud):
        """设置CANFD数据波特率
        n:{1,2}
        baud:{500kbps|1Mbps|2Mbps|5Mbps|8Mbps|10Mbps|CUSTom[,<value>]}
        value:100000~10000000"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:CANF:BAUDD %s" % (str(n), baud)
            self.write(command)

    def get_decode_canfd_bauddata(self, n):
        """获取CANF数据波特率
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:CANF:BAUDD?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_iis_latchege(self,n,type):
        """设置I2S边沿类型
        n:{1,2}
        type:{RISing|FALLing}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:LATC %s" % (str(n), type)
            self.write(command)

    def get_decode_iis_latchege(self, n):
        """获取I2S边沿类型
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:LATC?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_i2s_leftch(self,n,type):
        """设置I2S左声道类型
        n:{1,2}
        type:{LOW|HIGH}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:LCH %s" % (str(n), type)
            self.write(command)

    def get_decode_i2s_leftch(self, n):
        """获取I2S左声道类型
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:LCH?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_i2s_avriant(self,n,type):
        """设置I2S音频格式
        n:{1,2}
        type:{I2S|LJ|RJ}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:AVAR %s" % (str(n), type)
            self.write(command)

    def get_decode_i2s_avriant(self, n):
        """获取I2S音频格式
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:AVAR?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_i2s_startbit(self,n,bit):
        """设置I2S起始位
        n:{1.2}
        bit:0~31"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:SBIT %s" % (str(n),str( bit))
            self.write(command)

    def get_decode_i2s_startbit(self, n):
        """获取I2S起始位
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:SBIT?" % (str(n))
            return float(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def set_decode_i2s_annotate(self,n,channel):
        """设置I2S显示通道
        n:{1,2}
        channel:{ALL|LEFT|RIGHt}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:ANN %s" % (str(n), channel)
            self.write(command)

    def get_decode_i2s_annotate(self, n):
        """获取I2S显示通道
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:ANN?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_i2s_dlength(self,n,length):
        """设置I2S数据长度
        n:{1,2}
        length:1~32"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:DLEN %s" % (str(n), str(length))
            self.write(command)

    def get_decode_i2s_dlength(self, n):
        """获取I2S数据长度
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:IIS:DLEN?" % (str(n))
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    #----------------------------------ZDL1430下一主干版本支持--------------------------------------
    def set_decode_sent_msg_format(self, n, format):
        """设置sent 消息格式
        n:{1,2}
        format:{NIBBles|FSIGnal|SSERial|ESERial}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:FORM %s" % (str(n),format)
            self.write(command)

    def get_decode_sent_msg_format(self,n):
        """获取sent 消息格式"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:FORM?"% (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_sent_clock(self,n,times):
        """设置sent 时钟周期
        n:{1,2}
        times:5.00E-07~3.00E-04"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:CLOC %s" % (str(n), str(times))
            self.write(command)

    def get_decode_sent_clock(self,n):
        """获取sent 时钟周期
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:CLOC?" % (str(n))
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    def set_decode_sent_tolerance(self, n, tol):
        """设置sent 容差
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:TOL %s" % (str(n), str(tol))
            self.write(command)

    def get_decode_sent_tolerance(self, n):
        """获取sent 容差
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:TOL?" % (str(n))
            return int(self.query(command).rstrip())
        else:
            return _SCPI_NONE

    def set_decode_sent_idle(self, n, state):
        """设置sent 空闲状态
        state=["LOW","HIGH"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:IDLE %s" % (str(n), state)
            self.write(command)

    def get_decode_sent_idle(self, n):
        """获取sent 空闲状态
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:IDLE?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_sent_length(self, n, len):
        """设置sent 半字节数
        len:{3,4,5,6,7,8}
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:LENG %s" % (str(n), str(len))
            self.write(command)

    def get_decode_sent_length(self, n):
        """获取sent 半字节数
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:LENG?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_sent_crc(self, n, state):
        """设置sent CRC校验开关
        state=["OFF","ON"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:CRC %s" % (str(n), state)
            self.write(command)

    def get_decode_sent_crc(self, n):
        """获取sent CRC校验开关
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:CRC?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_sent_pause(self, n, state):
        """设置sent 可变暂停位开关
        state=["OFF","ON"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:PPUL %s" % (str(n), state)
            self.write(command)

    def get_decode_sent_pause(self, n):
        """获取sent 可变暂停位开关
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:SENT:PPUL?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_polarity(self, n, pol):
        """设置manchester 极性
        pol=["RISing","FALLing"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:POL %s" % (str(n), pol)
            self.write(command)

    def get_decode_manchester_polarity(self, n):
        """获取manchester 极性
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:POL?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_idle(self, n, state):
        """设置manchester 空闲状态
        state=["LOW","HIGH"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:IDLE %s" % (str(n), state)
            self.write(command)

    def get_decode_manchester_idle(self, n):
        """获取manchester 空闲状态
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:IDLE?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_ibits(self, n, num):
        """设置manchester 帧间隔
        num=[2-32]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:IBIT %s" % (str(n),  str(num))
            self.write(command)

    def get_decode_manchester_ibits(self, n):
        """获取manchester 帧间隔
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:IBIT?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_startedge(self, n, num):
        """设置manchester 起始沿
        num=[1-32]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:STAR %s" % (str(n),  str(num))
            self.write(command)

    def get_decode_manchester_startedge(self, n):
        """获取manchester 起始沿
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:STAR?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_field_size(self, n, field, num):
        """设置manchester各字段长度
        n:{1,2}
        field:{SYNC|HEAD|TRAIL|WORD|DATA}
        num:[0-32]"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:MANC:{}SIZ {}".format(n, field[0], num)
            self.write(command)

    def get_decode_manchester_field_size(self, n, field):
        """获取manchester各字段长度
        n:{1,2}
        field:{SYNC|HEAD|TRAIL|WORD|DATA}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS{}:MANC:{}SIZ?".format(n, field[0])
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_decode_manchester_display_format(self, n, format):
        """设置manchester 显示格式
        format=["WORD,"BIT"]
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:DISP %s" % (str(n), format)
            self.write(command)

    def get_decode_manchester_display_format(self, n):
        """获取manchester 显示格式
        n:{1,2}"""
        if self.SCPI_NEW_FLAG:
            command = "DEC:BUS%s:MANC:DISP?" % (str(n))
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    # -------------------------------------------------------------------------
    #
    # DVM
    #
    # -------------------------------------------------------------------------
    def set_dvm_switch(self,switch):
        """设置DVM开关
        switch:{ON|OFF}"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM {}".format(switch)
            self.write(command)

    def get_dvm_switch(self):
        """获取DVM开关"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_dvm_source(self,src):
        """设置DVM测量源
        src:{Cx}"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM:SOURce {}".format(src)
            self.write(command)

    def get_dvm_source(self):
        """获取DVM测量源"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM:SOURce?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_dvm_mode(self,mode):
        """设置DVM测量模式
        mode:{DCavg|DCRMs|ACRMs|PKPK|AMPLitude|FREQuency|PERiod}"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM:MODE {}".format(mode)
            self.write(command)

    def get_dvm_mode(self):
        """获取DVM测量模式"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM:MODE?"
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def get_dvm_value(self):
        """获取DVM测量值"""
        if self.SCPI_NEW_FLAG:
            command = ":DVM:CURRent?"
            return float(self.query(command).rstrip())
        else:
            return _MEAERROR

    # -------------------------------------------------------------------------
    #
    # Memory
    #
    # -------------------------------------------------------------------------
    def set_memory_switch(self, n, state):
        """设置memory开关
            state:{ON|OFF}"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:SWIT {}".format(n, state)
            self.write(command)

    def get_memory_switch(self, n):
        """获取memory开关"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:SWIT?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_improt(self, n, source):
        """设置memory improt
        source:C<x>,Z<x>,F<x>,M<x>,path:<x>.bin"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:IMP {}".format(n, source)
            self.write(command)

    def set_memory_label_switch(self, n, state):
        """设置memory开关
            state:{ON|OFF}"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:LAB {}".format(n, state)
            self.write(command)

    def get_memory_label_switch(self, n):
        """获取memory开关"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:LAB?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_label_test(self, n, test):
        """设置memory 标签文本
        test:string(length linmit:20)"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:LAB:TEXT {}".format(n, test)
            self.write(command)

    def get_memory_label_test(self, n):
        """获取memory 标签文本"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:LAB:TEXT?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_vertical_position(self, n, offset):
        """设置memory 垂直位置"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:VERT:POS {}".format(n, offset)
            self.write(command)

    def get_memory_vertical_position(self, n):
        """获取memory 垂直位置"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:VERT:POS?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_vertical_scale(self, n, scale):
        """设置memory 垂直档位"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:VERT:SCAL {}".format(n, scale)
            self.write(command)

    def get_memory_vertical_scale(self, n):
        """获取memory 垂直档位"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:VERT:SCAL?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_horizontal_position(self, n, value):
        """设置memory 水平位置"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:POS {}".format(n, value)
            self.write(command)

    def get_memory_horizontal_position(self, n):
        """获取memory 水平位置"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:POS?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_horizontal_scale(self, n, scale):
        """设置memory 水平档位"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:SCAL {}".format(n, scale)
            self.write(command)

    def get_memory_horizontal_scale(self, n):
        """获取memory 水平档位"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:SCAL?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def set_memory_horizontal_sync(self, n, state):
        """设置memory 水平同步"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:SYNC {}".format(n, state)
            self.write(command)

    def get_memory_horizontal_sync(self, n):
        """获取memory 水平同步"""
        if self.SCPI_NEW_FLAG:
            command = "MEM{}:HOR:SYNC?".format(n)
            return self.query(command).rstrip()
        else:
            return _SCPI_NONE

    def ConfigureChannel(self,chan,range,ofst,cpl,probe,enable):
        """chan=["C1","C2","C3","C4"],
        range=float,
        ofst=float,
        cpl=["AC","DC","GND"],
        probe=float,
        enable=["ON","OFF"]"""
        self.set_ch_trace_status(chan,enable)
        self.set_ch_probe(chan,probe)
        self.set_ch_vdiv(chan,range)
        self.set_ch_offset(chan, ofst)
        self.set_ch_coupl(chan,cpl)

    def wait_for_acquire_complete(self,timeout):
        """timeout:s"""
        isReady = False
        mode = self.get_trig_mode().upper()
        startTime = time.time()
        while True:
            time.sleep(0.1)
            if mode == "SINGLE":
                state = self.get_wave_sample_state()
                if ("Stop" in state):
                    isReady = True
                    break
                else:
                    if time.time() - startTime >= timeout:
                        print("single acauire_complete timeout")
                        break
            else:
                rtn = int(self.query("INR?").strip())
                if (rtn & 0x01):
                    isReady = True
                    break
                else:
                    if time.time() - startTime >= timeout:
                        print("acauire_complete timeout")
                        break
        return isReady

    def screen_shot(self, format, file):
        """截屏保存到指定文件
        format = ["BMP", "PNG"]
        fle:指定保存图片路径，需带尾缀"""
        self.write("PRINt? {}".format(format))
        bin_str = self.read_raw()
        f = open(file, "wb")
        f.write(bin_str)
        f.flush()
        f.close()
        
# -------------------------------------------------------------------------------
# import pylab as pl
TBFULL_FLOAT = [100E-12, 200E-12, 500E-12, 1E-9, 2E-09,
                5E-9, 10E-9, 20E-9,
                50E-9, 100E-9, 200E-9, 500E-9, 1E-6, 2E-6, 5E-6, 10E-6, 20E-6, 50E-6, 100E-6, 200E-6,
                500E-6, 1E-3, 2E-3, 5E-3, 10E-3, 20E-3,
                50E-3, 100E-3, 200E-3, 500E-3, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]

if __name__ == "__main__":
    volt_value = []
    for i in range(0,5):
        print("-------test count:{}------".format(i))
        dev = LibSDS("USB0::0xF4EC::0x1013::SDS6LA2D6R0026::INSTR")#ZDL+:USB0::0xF4EC::0x1013::SDS62DDD6R0323::INSTR
        dev.ConfigureChannel("C1",0.01,0,"DC",1,"ON")
        dev.set_memory_depth("5M")
        dev.set_timebase(0.0002)
        dev.set_timebase_delay(-0.0004)
        dev.set_trig_type("EDGE","C1")
        dev.set_trig_level(0.005,"C1","EDGE")
        dev.set_trigger_slope("RISing")
        dev.wait_for_acquire_complete(10)

        wf_param = dev.get_wvfm_preamble("C1")
        wf_param["tdiv"] = TBFULL_FLOAT[wf_param["tdiv"]]
        print(wf_param)
        code_list = dev.get_wvfm_real_data_16bit("C1", wf_param["adc_bit"])
        for idx in range(0, len(code_list)):
            volt_value.append(code_list[idx] / wf_param["code"] * float(wf_param["vdiv"]) - float(wf_param["offset"]))
        print(len(volt_value))
        continue

    time_value = [i for i in range(0, len(volt_value))]
    pl.figure(figsize=(7, 5))
    pl.plot(time_value, volt_value, markersize=2, label=u"Y-T")
    pl.legend()
    pl.grid()
    pl.show()
